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_fetch_get_stock_xdxr | 除权除息 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_stock_xdxr(code, ip=None, port=None):
'除权除息'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
market_code = _select_market_code(code)
with api.connect(ip, port):
category = {
'1': '除权除息', '2': '送配股上市', '3': '非流通股上市', '4': '未知股本变动', '5': '股本变化',
'6': '增发新股', '7': '股份回购', '8': '增发新股上市', '9': '转配股上市', '10': '可转债上市',
'11': '扩缩股', '12': '非流通股缩股', '13': '送认购权证', '14': '送认沽权证'}
data = api.to_df(api.get_xdxr_info(market_code, code))
if len(data) >= 1:
data = data \
.assign(date=pd.to_datetime(data[['year', 'month', 'day']])) \
.drop(['year', 'month', 'day'], axis=1) \
.assign(category_meaning=data['category'].apply(lambda x: category[str(x)])) \
.assign(code=str(code)) \
.rename(index=str, columns={'panhouliutong': 'liquidity_after',
'panqianliutong': 'liquidity_before', 'houzongguben': 'shares_after',
'qianzongguben': 'shares_before'}) \
.set_index('date', drop=False, inplace=False)
return data.assign(date=data['date'].apply(lambda x: str(x)[0:10]))
else:
return None | def QA_fetch_get_stock_xdxr(code, ip=None, port=None):
'除权除息'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
market_code = _select_market_code(code)
with api.connect(ip, port):
category = {
'1': '除权除息', '2': '送配股上市', '3': '非流通股上市', '4': '未知股本变动', '5': '股本变化',
'6': '增发新股', '7': '股份回购', '8': '增发新股上市', '9': '转配股上市', '10': '可转债上市',
'11': '扩缩股', '12': '非流通股缩股', '13': '送认购权证', '14': '送认沽权证'}
data = api.to_df(api.get_xdxr_info(market_code, code))
if len(data) >= 1:
data = data \
.assign(date=pd.to_datetime(data[['year', 'month', 'day']])) \
.drop(['year', 'month', 'day'], axis=1) \
.assign(category_meaning=data['category'].apply(lambda x: category[str(x)])) \
.assign(code=str(code)) \
.rename(index=str, columns={'panhouliutong': 'liquidity_after',
'panqianliutong': 'liquidity_before', 'houzongguben': 'shares_after',
'qianzongguben': 'shares_before'}) \
.set_index('date', drop=False, inplace=False)
return data.assign(date=data['date'].apply(lambda x: str(x)[0:10]))
else:
return None | [
"除权除息"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1004-L1027 | [
"def",
"QA_fetch_get_stock_xdxr",
"(",
"code",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
"api",
"=",
"TdxHq_API",
"(",
")",
"market_code",
"=",
"_select_market_co... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_stock_info | 股票基本信息 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_stock_info(code, ip=None, port=None):
'股票基本信息'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
market_code = _select_market_code(code)
with api.connect(ip, port):
return api.to_df(api.get_finance_info(market_code, code)) | def QA_fetch_get_stock_info(code, ip=None, port=None):
'股票基本信息'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
market_code = _select_market_code(code)
with api.connect(ip, port):
return api.to_df(api.get_finance_info(market_code, code)) | [
"股票基本信息"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1030-L1036 | [
"def",
"QA_fetch_get_stock_info",
"(",
"code",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
"api",
"=",
"TdxHq_API",
"(",
")",
"market_code",
"=",
"_select_market_co... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_stock_block | 板块数据 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_stock_block(ip=None, port=None):
'板块数据'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat([api.to_df(api.get_and_parse_block_info("block_gn.dat")).assign(type='gn'),
api.to_df(api.get_and_parse_block_info(
"block.dat")).assign(type='yb'),
api.to_df(api.get_and_parse_block_info(
"block_zs.dat")).assign(type='zs'),
api.to_df(api.get_and_parse_block_info("block_fg.dat")).assign(type='fg')])
if len(data) > 10:
return data.assign(source='tdx').drop(['block_type', 'code_index'], axis=1).set_index('code', drop=False,
inplace=False).drop_duplicates()
else:
QA_util_log_info('Wrong with fetch block ') | def QA_fetch_get_stock_block(ip=None, port=None):
'板块数据'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat([api.to_df(api.get_and_parse_block_info("block_gn.dat")).assign(type='gn'),
api.to_df(api.get_and_parse_block_info(
"block.dat")).assign(type='yb'),
api.to_df(api.get_and_parse_block_info(
"block_zs.dat")).assign(type='zs'),
api.to_df(api.get_and_parse_block_info("block_fg.dat")).assign(type='fg')])
if len(data) > 10:
return data.assign(source='tdx').drop(['block_type', 'code_index'], axis=1).set_index('code', drop=False,
inplace=False).drop_duplicates()
else:
QA_util_log_info('Wrong with fetch block ') | [
"板块数据"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1039-L1056 | [
"def",
"QA_fetch_get_stock_block",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
"api",
"=",
"TdxHq_API",
"(",
")",
"with",
"api",
".",
"connect",
"(",
"ip",
",",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_extensionmarket_list | 期货代码list | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_extensionmarket_list(ip=None, port=None):
'期货代码list'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
with apix.connect(ip, port):
num = apix.get_instrument_count()
return pd.concat([apix.to_df(
apix.get_instrument_info((int(num / 500) - i) * 500, 500))
for i in range(int(num / 500) + 1)], axis=0).set_index('code', drop=False) | def QA_fetch_get_extensionmarket_list(ip=None, port=None):
'期货代码list'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
with apix.connect(ip, port):
num = apix.get_instrument_count()
return pd.concat([apix.to_df(
apix.get_instrument_info((int(num / 500) - i) * 500, 500))
for i in range(int(num / 500) + 1)], axis=0).set_index('code', drop=False) | [
"期货代码list"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1172-L1180 | [
"def",
"QA_fetch_get_extensionmarket_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_extensionmarket_ip",
"(",
"ip",
",",
"port",
")",
"apix",
"=",
"TdxExHq_API",
"(",
")",
"with",
"apix",
".",
"connect",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_future_list | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
42 3 商品指数 TI
60 3 主力期货合约 MA
28 3 郑州商品 QZ
29 3 大连商品 QD
30 3 上海期货(原油+贵金属) QS
47 3 中金所期货 CZ
50 3 渤海商品 BH
76 3 齐鲁商品 QL
46 11 上海黄金(伦敦金T+D) SG | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_future_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
42 3 商品指数 TI
60 3 主力期货合约 MA
28 3 郑州商品 QZ
29 3 大连商品 QD
30 3 上海期货(原油+贵金属) QS
47 3 中金所期货 CZ
50 3 渤海商品 BH
76 3 齐鲁商品 QL
46 11 上海黄金(伦敦金T+D) SG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==42 or market==28 or market==29 or market==30 or market==47') | def QA_fetch_get_future_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
42 3 商品指数 TI
60 3 主力期货合约 MA
28 3 郑州商品 QZ
29 3 大连商品 QD
30 3 上海期货(原油+贵金属) QS
47 3 中金所期货 CZ
50 3 渤海商品 BH
76 3 齐鲁商品 QL
46 11 上海黄金(伦敦金T+D) SG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==42 or market==28 or market==29 or market==30 or market==47') | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1183-L1208 | [
"def",
"QA_fetch_get_future_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"extensi... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_globalindex_list | 全球指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
37 11 全球指数(静态) FW
12 5 国际指数 WI | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_globalindex_list(ip=None, port=None):
"""全球指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
37 11 全球指数(静态) FW
12 5 国际指数 WI
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==12 or market==37') | def QA_fetch_get_globalindex_list(ip=None, port=None):
"""全球指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
37 11 全球指数(静态) FW
12 5 国际指数 WI
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==12 or market==37') | [
"全球指数列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1211-L1227 | [
"def",
"QA_fetch_get_globalindex_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"ex... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_goods_list | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
42 3 商品指数 TI
60 3 主力期货合约 MA
28 3 郑州商品 QZ
29 3 大连商品 QD
30 3 上海期货(原油+贵金属) QS
47 3 中金所期货 CZ
50 3 渤海商品 BH
76 3 齐鲁商品 QL
46 11 上海黄金(伦敦金T+D) SG | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_goods_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
42 3 商品指数 TI
60 3 主力期货合约 MA
28 3 郑州商品 QZ
29 3 大连商品 QD
30 3 上海期货(原油+贵金属) QS
47 3 中金所期货 CZ
50 3 渤海商品 BH
76 3 齐鲁商品 QL
46 11 上海黄金(伦敦金T+D) SG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==50 or market==76 or market==46') | def QA_fetch_get_goods_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
42 3 商品指数 TI
60 3 主力期货合约 MA
28 3 郑州商品 QZ
29 3 大连商品 QD
30 3 上海期货(原油+贵金属) QS
47 3 中金所期货 CZ
50 3 渤海商品 BH
76 3 齐鲁商品 QL
46 11 上海黄金(伦敦金T+D) SG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==50 or market==76 or market==46') | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1230-L1255 | [
"def",
"QA_fetch_get_goods_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"extensio... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_globalfuture_list | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
14 3 伦敦金属 LM
15 3 伦敦石油 IP
16 3 纽约商品 CO
17 3 纽约石油 NY
18 3 芝加哥谷 CB
19 3 东京工业品 TO
20 3 纽约期货 NB
77 3 新加坡期货 SX
39 3 马来期货 ML | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_globalfuture_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
14 3 伦敦金属 LM
15 3 伦敦石油 IP
16 3 纽约商品 CO
17 3 纽约石油 NY
18 3 芝加哥谷 CB
19 3 东京工业品 TO
20 3 纽约期货 NB
77 3 新加坡期货 SX
39 3 马来期货 ML
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query(
'market==14 or market==15 or market==16 or market==17 or market==18 or market==19 or market==20 or market==77 or market==39') | def QA_fetch_get_globalfuture_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
14 3 伦敦金属 LM
15 3 伦敦石油 IP
16 3 纽约商品 CO
17 3 纽约石油 NY
18 3 芝加哥谷 CB
19 3 东京工业品 TO
20 3 纽约期货 NB
77 3 新加坡期货 SX
39 3 马来期货 ML
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query(
'market==14 or market==15 or market==16 or market==17 or market==18 or market==19 or market==20 or market==77 or market==39') | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1258-L1282 | [
"def",
"QA_fetch_get_globalfuture_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"e... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_hkstock_list | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_hkstock_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==31 or market==48') | def QA_fetch_get_hkstock_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==31 or market==48') | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1285-L1305 | [
"def",
"QA_fetch_get_hkstock_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"extens... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_hkindex_list | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_hkindex_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==27') | def QA_fetch_get_hkindex_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==27') | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1308-L1328 | [
"def",
"QA_fetch_get_hkindex_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"extens... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_hkfund_list | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_hkfund_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==49') | def QA_fetch_get_hkfund_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 KT
43 1 B股转H股 HB
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==49') | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1331-L1351 | [
"def",
"QA_fetch_get_hkfund_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"extensi... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_usstock_list | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 美股 USA STOCK
74 13 美国股票 US
40 11 中国概念股 CH
41 11 美股知名公司 MG | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_usstock_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 美股 USA STOCK
74 13 美国股票 US
40 11 中国概念股 CH
41 11 美股知名公司 MG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==74 or market==40 or market==41') | def QA_fetch_get_usstock_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 美股 USA STOCK
74 13 美国股票 US
40 11 中国概念股 CH
41 11 美股知名公司 MG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==74 or market==40 or market==41') | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1354-L1373 | [
"def",
"QA_fetch_get_usstock_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"extens... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_macroindex_list | 宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_macroindex_list(ip=None, port=None):
"""宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==38') | def QA_fetch_get_macroindex_list(ip=None, port=None):
"""宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==38') | [
"宏观指标列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1376-L1391 | [
"def",
"QA_fetch_get_macroindex_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"ext... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_option_list | 期权列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 期权 OPTION
1 12 临时期权(主要是50ETF)
4 12 郑州商品期权 OZ
5 12 大连商品期权 OD
6 12 上海商品期权 OS
7 12 中金所期权 OJ
8 12 上海股票期权 QQ
9 12 深圳股票期权 (推测) | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_option_list(ip=None, port=None):
"""期权列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 期权 OPTION
1 12 临时期权(主要是50ETF)
4 12 郑州商品期权 OZ
5 12 大连商品期权 OD
6 12 上海商品期权 OS
7 12 中金所期权 OJ
8 12 上海股票期权 QQ
9 12 深圳股票期权 (推测)
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('category==12 and market!=1') | def QA_fetch_get_option_list(ip=None, port=None):
"""期权列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 期权 OPTION
1 12 临时期权(主要是50ETF)
4 12 郑州商品期权 OZ
5 12 大连商品期权 OD
6 12 上海商品期权 OS
7 12 中金所期权 OJ
8 12 上海股票期权 QQ
9 12 深圳股票期权 (推测)
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('category==12 and market!=1') | [
"期权列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1394-L1416 | [
"def",
"QA_fetch_get_option_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"extensi... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_option_contract_time_to_market | #🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_option_contract_time_to_market():
'''
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
'''
fix here :
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
result['meaningful_name'] = None
C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
'''
# df = pd.DataFrame()
rows = []
result['meaningful_name'] = None
for idx in result.index:
# pprint.pprint((idx))
strCategory = result.loc[idx, "category"]
strMarket = result.loc[idx, "market"]
strCode = result.loc[idx, "code"] # 10001215
strName = result.loc[idx, 'name'] # 510050C9M03200
strDesc = result.loc[idx, 'desc'] # 10001215
if strName.startswith("510050"):
# print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )
if strName.startswith("510050C"):
putcall = '50ETF,认购期权'
elif strName.startswith("510050P"):
putcall = '50ETF,认沽期权'
else:
putcall = "Unkown code name : " + strName
expireMonth = strName[7:8]
if expireMonth == 'A':
expireMonth = "10月"
elif expireMonth == 'B':
expireMonth = "11月"
elif expireMonth == 'C':
expireMonth = "12月"
else:
expireMonth = expireMonth + '月'
# 第12位期初设为“M”,并根据合约调整次数按照“A”至“Z”依序变更,如变更为“A”表示期权合约发生首次调整,变更为“B”表示期权合约发生第二次调整,依此类推;
# fix here : M ??
if strName[8:9] == "M":
adjust = "未调整"
elif strName[8:9] == 'A':
adjust = " 第1次调整"
elif strName[8:9] == 'B':
adjust = " 第2调整"
elif strName[8:9] == 'C':
adjust = " 第3次调整"
elif strName[8:9] == 'D':
adjust = " 第4次调整"
elif strName[8:9] == 'E':
adjust = " 第5次调整"
elif strName[8:9] == 'F':
adjust = " 第6次调整"
elif strName[8:9] == 'G':
adjust = " 第7次调整"
elif strName[8:9] == 'H':
adjust = " 第8次调整"
elif strName[8:9] == 'I':
adjust = " 第9次调整"
elif strName[8:9] == 'J':
adjust = " 第10次调整"
else:
adjust = " 第10次以上的调整,调整代码 %s" + strName[8:9]
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % (
putcall, expireMonth, adjust, executePrice)
row = result.loc[idx]
rows.append(row)
elif strName.startswith("SR"):
# print("SR")
# SR1903-P-6500
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "白糖,认沽期权"
elif put_or_call == "C":
putcall = "白糖,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("CU"):
# print("CU")
# print("SR")
# SR1903-P-6500
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "铜,认沽期权"
elif put_or_call == "C":
putcall = "铜,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
# todo 新增期权品种 棉花,玉米, 天然橡胶
elif strName.startswith("RU"):
# print("M")
# print(strName)
##
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "天然橡胶,认沽期权"
elif put_or_call == "C":
putcall = "天然橡胶,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("CF"):
# print("M")
# print(strName)
##
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "棉花,认沽期权"
elif put_or_call == "C":
putcall = "棉花,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("M"):
# print("M")
# print(strName)
##
expireYear = strName[1:3]
expireMonth = strName[3:5]
put_or_call = strName[6:7]
if put_or_call == "P":
putcall = "豆粕,认沽期权"
elif put_or_call == "C":
putcall = "豆粕,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[8:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("C") and strName[1] != 'F' and strName[1] != 'U':
# print("M")
# print(strName)
##
expireYear = strName[1:3]
expireMonth = strName[3:5]
put_or_call = strName[6:7]
if put_or_call == "P":
putcall = "玉米,认沽期权"
elif put_or_call == "C":
putcall = "玉米,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[8:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
else:
print("未知类型合约")
print(strName)
return rows | def QA_fetch_get_option_contract_time_to_market():
'''
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
'''
fix here :
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
result['meaningful_name'] = None
C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
'''
# df = pd.DataFrame()
rows = []
result['meaningful_name'] = None
for idx in result.index:
# pprint.pprint((idx))
strCategory = result.loc[idx, "category"]
strMarket = result.loc[idx, "market"]
strCode = result.loc[idx, "code"] # 10001215
strName = result.loc[idx, 'name'] # 510050C9M03200
strDesc = result.loc[idx, 'desc'] # 10001215
if strName.startswith("510050"):
# print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )
if strName.startswith("510050C"):
putcall = '50ETF,认购期权'
elif strName.startswith("510050P"):
putcall = '50ETF,认沽期权'
else:
putcall = "Unkown code name : " + strName
expireMonth = strName[7:8]
if expireMonth == 'A':
expireMonth = "10月"
elif expireMonth == 'B':
expireMonth = "11月"
elif expireMonth == 'C':
expireMonth = "12月"
else:
expireMonth = expireMonth + '月'
# 第12位期初设为“M”,并根据合约调整次数按照“A”至“Z”依序变更,如变更为“A”表示期权合约发生首次调整,变更为“B”表示期权合约发生第二次调整,依此类推;
# fix here : M ??
if strName[8:9] == "M":
adjust = "未调整"
elif strName[8:9] == 'A':
adjust = " 第1次调整"
elif strName[8:9] == 'B':
adjust = " 第2调整"
elif strName[8:9] == 'C':
adjust = " 第3次调整"
elif strName[8:9] == 'D':
adjust = " 第4次调整"
elif strName[8:9] == 'E':
adjust = " 第5次调整"
elif strName[8:9] == 'F':
adjust = " 第6次调整"
elif strName[8:9] == 'G':
adjust = " 第7次调整"
elif strName[8:9] == 'H':
adjust = " 第8次调整"
elif strName[8:9] == 'I':
adjust = " 第9次调整"
elif strName[8:9] == 'J':
adjust = " 第10次调整"
else:
adjust = " 第10次以上的调整,调整代码 %s" + strName[8:9]
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % (
putcall, expireMonth, adjust, executePrice)
row = result.loc[idx]
rows.append(row)
elif strName.startswith("SR"):
# print("SR")
# SR1903-P-6500
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "白糖,认沽期权"
elif put_or_call == "C":
putcall = "白糖,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("CU"):
# print("CU")
# print("SR")
# SR1903-P-6500
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "铜,认沽期权"
elif put_or_call == "C":
putcall = "铜,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
# todo 新增期权品种 棉花,玉米, 天然橡胶
elif strName.startswith("RU"):
# print("M")
# print(strName)
##
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "天然橡胶,认沽期权"
elif put_or_call == "C":
putcall = "天然橡胶,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("CF"):
# print("M")
# print(strName)
##
expireYear = strName[2:4]
expireMonth = strName[4:6]
put_or_call = strName[7:8]
if put_or_call == "P":
putcall = "棉花,认沽期权"
elif put_or_call == "C":
putcall = "棉花,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("M"):
# print("M")
# print(strName)
##
expireYear = strName[1:3]
expireMonth = strName[3:5]
put_or_call = strName[6:7]
if put_or_call == "P":
putcall = "豆粕,认沽期权"
elif put_or_call == "C":
putcall = "豆粕,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[8:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
elif strName.startswith("C") and strName[1] != 'F' and strName[1] != 'U':
# print("M")
# print(strName)
##
expireYear = strName[1:3]
expireMonth = strName[3:5]
put_or_call = strName[6:7]
if put_or_call == "P":
putcall = "玉米,认沽期权"
elif put_or_call == "C":
putcall = "玉米,认购期权"
else:
putcall = "Unkown code name : " + strName
executePrice = strName[8:]
result.loc[idx, 'meaningful_name'] = '%s,到期年月份:%s%s,行权价:%s' % (
putcall, expireYear, expireMonth, executePrice)
row = result.loc[idx]
rows.append(row)
pass
else:
print("未知类型合约")
print(strName)
return rows | [
"#🛠todo",
"获取期权合约的上市日期",
"?",
"暂时没有。",
":",
"return",
":",
"list",
"Series"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1419-L1646 | [
"def",
"QA_fetch_get_option_contract_time_to_market",
"(",
")",
":",
"result",
"=",
"QA_fetch_get_option_list",
"(",
"'tdx'",
")",
"# pprint.pprint(result)",
"# category market code name desc code",
"'''\n fix here : \n See the caveats in the documentation: http://pandas.pydata.or... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_option_50etf_contract_time_to_market | #🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_option_50etf_contract_time_to_market():
'''
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
'''
fix here :
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
result['meaningful_name'] = None
C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
'''
# df = pd.DataFrame()
rows = []
result['meaningful_name'] = None
for idx in result.index:
# pprint.pprint((idx))
strCategory = result.loc[idx, "category"]
strMarket = result.loc[idx, "market"]
strCode = result.loc[idx, "code"] # 10001215
strName = result.loc[idx, 'name'] # 510050C9M03200
strDesc = result.loc[idx, 'desc'] # 10001215
if strName.startswith("510050"):
# print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )
if strName.startswith("510050C"):
putcall = '50ETF,认购期权'
elif strName.startswith("510050P"):
putcall = '50ETF,认沽期权'
else:
putcall = "Unkown code name : " + strName
expireMonth = strName[7:8]
if expireMonth == 'A':
expireMonth = "10月"
elif expireMonth == 'B':
expireMonth = "11月"
elif expireMonth == 'C':
expireMonth = "12月"
else:
expireMonth = expireMonth + '月'
# 第12位期初设为“M”,并根据合约调整次数按照“A”至“Z”依序变更,如变更为“A”表示期权合约发生首次调整,变更为“B”表示期权合约发生第二次调整,依此类推;
# fix here : M ??
if strName[8:9] == "M":
adjust = "未调整"
elif strName[8:9] == 'A':
adjust = " 第1次调整"
elif strName[8:9] == 'B':
adjust = " 第2调整"
elif strName[8:9] == 'C':
adjust = " 第3次调整"
elif strName[8:9] == 'D':
adjust = " 第4次调整"
elif strName[8:9] == 'E':
adjust = " 第5次调整"
elif strName[8:9] == 'F':
adjust = " 第6次调整"
elif strName[8:9] == 'G':
adjust = " 第7次调整"
elif strName[8:9] == 'H':
adjust = " 第8次调整"
elif strName[8:9] == 'I':
adjust = " 第9次调整"
elif strName[8:9] == 'J':
adjust = " 第10次调整"
else:
adjust = " 第10次以上的调整,调整代码 %s" + strName[8:9]
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % (
putcall, expireMonth, adjust, executePrice)
row = result.loc[idx]
rows.append(row)
return rows | def QA_fetch_get_option_50etf_contract_time_to_market():
'''
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
'''
fix here :
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
result['meaningful_name'] = None
C:\work_new\QUANTAXIS\QUANTAXIS\QAFetch\QATdx.py:1468: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
'''
# df = pd.DataFrame()
rows = []
result['meaningful_name'] = None
for idx in result.index:
# pprint.pprint((idx))
strCategory = result.loc[idx, "category"]
strMarket = result.loc[idx, "market"]
strCode = result.loc[idx, "code"] # 10001215
strName = result.loc[idx, 'name'] # 510050C9M03200
strDesc = result.loc[idx, 'desc'] # 10001215
if strName.startswith("510050"):
# print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )
if strName.startswith("510050C"):
putcall = '50ETF,认购期权'
elif strName.startswith("510050P"):
putcall = '50ETF,认沽期权'
else:
putcall = "Unkown code name : " + strName
expireMonth = strName[7:8]
if expireMonth == 'A':
expireMonth = "10月"
elif expireMonth == 'B':
expireMonth = "11月"
elif expireMonth == 'C':
expireMonth = "12月"
else:
expireMonth = expireMonth + '月'
# 第12位期初设为“M”,并根据合约调整次数按照“A”至“Z”依序变更,如变更为“A”表示期权合约发生首次调整,变更为“B”表示期权合约发生第二次调整,依此类推;
# fix here : M ??
if strName[8:9] == "M":
adjust = "未调整"
elif strName[8:9] == 'A':
adjust = " 第1次调整"
elif strName[8:9] == 'B':
adjust = " 第2调整"
elif strName[8:9] == 'C':
adjust = " 第3次调整"
elif strName[8:9] == 'D':
adjust = " 第4次调整"
elif strName[8:9] == 'E':
adjust = " 第5次调整"
elif strName[8:9] == 'F':
adjust = " 第6次调整"
elif strName[8:9] == 'G':
adjust = " 第7次调整"
elif strName[8:9] == 'H':
adjust = " 第8次调整"
elif strName[8:9] == 'I':
adjust = " 第9次调整"
elif strName[8:9] == 'J':
adjust = " 第10次调整"
else:
adjust = " 第10次以上的调整,调整代码 %s" + strName[8:9]
executePrice = strName[9:]
result.loc[idx, 'meaningful_name'] = '%s,到期月份:%s,%s,行权价:%s' % (
putcall, expireMonth, adjust, executePrice)
row = result.loc[idx]
rows.append(row)
return rows | [
"#🛠todo",
"获取期权合约的上市日期",
"?",
"暂时没有。",
":",
"return",
":",
"list",
"Series"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1649-L1730 | [
"def",
"QA_fetch_get_option_50etf_contract_time_to_market",
"(",
")",
":",
"result",
"=",
"QA_fetch_get_option_list",
"(",
"'tdx'",
")",
"# pprint.pprint(result)",
"# category market code name desc code",
"'''\n fix here : \n See the caveats in the documentation: http://pandas.pyd... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_commodity_option_CF_contract_time_to_market | 铜期权 CU 开头 上期证
豆粕 M开头 大商所
白糖 SR开头 郑商所
测试中发现,行情不太稳定 ? 是 通达信 IP 的问题 ? | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_commodity_option_CF_contract_time_to_market():
'''
铜期权 CU 开头 上期证
豆粕 M开头 大商所
白糖 SR开头 郑商所
测试中发现,行情不太稳定 ? 是 通达信 IP 的问题 ?
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
# df = pd.DataFrame()
rows = []
result['meaningful_name'] = None
for idx in result.index:
# pprint.pprint((idx))
strCategory = result.loc[idx, "category"]
strMarket = result.loc[idx, "market"]
strCode = result.loc[idx, "code"] #
strName = result.loc[idx, 'name'] #
strDesc = result.loc[idx, 'desc'] #
# 如果同时获取, 不同的 期货交易所数据, pytdx会 connection close 连接中断?
# if strName.startswith("CU") or strName.startswith("M") or strName.startswith('SR'):
if strName.startswith("CF"):
# print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )
row = result.loc[idx]
rows.append(row)
return rows
pass | def QA_fetch_get_commodity_option_CF_contract_time_to_market():
'''
铜期权 CU 开头 上期证
豆粕 M开头 大商所
白糖 SR开头 郑商所
测试中发现,行情不太稳定 ? 是 通达信 IP 的问题 ?
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
# df = pd.DataFrame()
rows = []
result['meaningful_name'] = None
for idx in result.index:
# pprint.pprint((idx))
strCategory = result.loc[idx, "category"]
strMarket = result.loc[idx, "market"]
strCode = result.loc[idx, "code"] #
strName = result.loc[idx, 'name'] #
strDesc = result.loc[idx, 'desc'] #
# 如果同时获取, 不同的 期货交易所数据, pytdx会 connection close 连接中断?
# if strName.startswith("CU") or strName.startswith("M") or strName.startswith('SR'):
if strName.startswith("CF"):
# print(strCategory,' ', strMarket, ' ', strCode, ' ', strName, ' ', strDesc, )
row = result.loc[idx]
rows.append(row)
return rows
pass | [
"铜期权",
"CU",
"开头",
"上期证",
"豆粕",
"M开头",
"大商所",
"白糖",
"SR开头",
"郑商所",
"测试中发现,行情不太稳定",
"?",
"是",
"通达信",
"IP",
"的问题",
"?"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1733-L1765 | [
"def",
"QA_fetch_get_commodity_option_CF_contract_time_to_market",
"(",
")",
":",
"result",
"=",
"QA_fetch_get_option_list",
"(",
"'tdx'",
")",
"# pprint.pprint(result)",
"# category market code name desc code",
"# df = pd.DataFrame()",
"rows",
"=",
"[",
"]",
"result",
"[",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_exchangerate_list | 汇率列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 汇率 EXCHANGERATE
10 4 基本汇率 FE
11 4 交叉汇率 FX | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_exchangerate_list(ip=None, port=None):
"""汇率列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 汇率 EXCHANGERATE
10 4 基本汇率 FE
11 4 交叉汇率 FX
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==10 or market==11').query('category==4') | def QA_fetch_get_exchangerate_list(ip=None, port=None):
"""汇率列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 汇率 EXCHANGERATE
10 4 基本汇率 FE
11 4 交叉汇率 FX
"""
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
return extension_market_list.query('market==10 or market==11').query('category==4') | [
"汇率列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1938-L1955 | [
"def",
"QA_fetch_get_exchangerate_list",
"(",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"global",
"extension_market_list",
"extension_market_list",
"=",
"QA_fetch_get_extensionmarket_list",
"(",
")",
"if",
"extension_market_list",
"is",
"None",
"else",
"e... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_future_day | 期货数据 日线 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_future_day(code, start_date, end_date, frequence='day', ip=None, port=None):
'期货数据 日线'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
start_date = str(start_date)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
with apix.connect(ip, port):
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
data = pd.concat(
[apix.to_df(apix.get_instrument_bars(
_select_type(frequence),
int(code_market.market),
str(code),
(int(lens / 700) - i) * 700, 700)) for i in range(int(lens / 700) + 1)],
axis=0)
try:
# 获取商品期货会报None
data = data.assign(date=data['datetime'].apply(lambda x: str(x[0:10]))).assign(code=str(code)) \
.assign(date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(str(x)[0:10]))).set_index('date',
drop=False,
inplace=False)
except Exception as exp:
print("code is ", code)
print(exp.__str__)
return None
return data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[start_date:end_date].assign(
date=data['date'].apply(lambda x: str(x)[0:10])) | def QA_fetch_get_future_day(code, start_date, end_date, frequence='day', ip=None, port=None):
'期货数据 日线'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
start_date = str(start_date)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
with apix.connect(ip, port):
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
data = pd.concat(
[apix.to_df(apix.get_instrument_bars(
_select_type(frequence),
int(code_market.market),
str(code),
(int(lens / 700) - i) * 700, 700)) for i in range(int(lens / 700) + 1)],
axis=0)
try:
# 获取商品期货会报None
data = data.assign(date=data['datetime'].apply(lambda x: str(x[0:10]))).assign(code=str(code)) \
.assign(date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(str(x)[0:10]))).set_index('date',
drop=False,
inplace=False)
except Exception as exp:
print("code is ", code)
print(exp.__str__)
return None
return data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[start_date:end_date].assign(
date=data['date'].apply(lambda x: str(x)[0:10])) | [
"期货数据",
"日线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1958-L1995 | [
"def",
"QA_fetch_get_future_day",
"(",
"code",
",",
"start_date",
",",
"end_date",
",",
"frequence",
"=",
"'day'",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_extensionmarket_ip",
"(",
"ip",
",",
"port",
")",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_future_min | 期货数据 分钟线 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_future_min(code, start, end, frequence='1min', ip=None, port=None):
'期货数据 分钟线'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
type_ = ''
start_date = str(start)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
if str(frequence) in ['5', '5m', '5min', 'five']:
frequence, type_ = 0, '5min'
lens = 48 * lens * 2.5
elif str(frequence) in ['1', '1m', '1min', 'one']:
frequence, type_ = 8, '1min'
lens = 240 * lens * 2.5
elif str(frequence) in ['15', '15m', '15min', 'fifteen']:
frequence, type_ = 1, '15min'
lens = 16 * lens * 2.5
elif str(frequence) in ['30', '30m', '30min', 'half']:
frequence, type_ = 2, '30min'
lens = 8 * lens * 2.5
elif str(frequence) in ['60', '60m', '60min', '1h']:
frequence, type_ = 3, '60min'
lens = 4 * lens * 2.5
if lens > 20800:
lens = 20800
# print(lens)
with apix.connect(ip, port):
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
data = pd.concat([apix.to_df(apix.get_instrument_bars(frequence, int(code_market.market), str(
code), (int(lens / 700) - i) * 700, 700)) for i in range(int(lens / 700) + 1)], axis=0)
# print(data)
# print(data.datetime)
data = data \
.assign(tradetime=data['datetime'].apply(str), code=str(code)) \
.assign(datetime=pd.to_datetime(data['datetime'].apply(QA_util_future_to_realdatetime, 1))) \
.drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \
.assign(date=data['datetime'].apply(lambda x: str(x)[0:10])) \
.assign(date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(x))) \
.assign(time_stamp=data['datetime'].apply(lambda x: QA_util_time_stamp(x))) \
.assign(type=type_).set_index('datetime', drop=False, inplace=False)
return data.assign(datetime=data['datetime'].apply(lambda x: str(x)))[start:end].sort_index() | def QA_fetch_get_future_min(code, start, end, frequence='1min', ip=None, port=None):
'期货数据 分钟线'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
type_ = ''
start_date = str(start)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
if str(frequence) in ['5', '5m', '5min', 'five']:
frequence, type_ = 0, '5min'
lens = 48 * lens * 2.5
elif str(frequence) in ['1', '1m', '1min', 'one']:
frequence, type_ = 8, '1min'
lens = 240 * lens * 2.5
elif str(frequence) in ['15', '15m', '15min', 'fifteen']:
frequence, type_ = 1, '15min'
lens = 16 * lens * 2.5
elif str(frequence) in ['30', '30m', '30min', 'half']:
frequence, type_ = 2, '30min'
lens = 8 * lens * 2.5
elif str(frequence) in ['60', '60m', '60min', '1h']:
frequence, type_ = 3, '60min'
lens = 4 * lens * 2.5
if lens > 20800:
lens = 20800
# print(lens)
with apix.connect(ip, port):
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
data = pd.concat([apix.to_df(apix.get_instrument_bars(frequence, int(code_market.market), str(
code), (int(lens / 700) - i) * 700, 700)) for i in range(int(lens / 700) + 1)], axis=0)
# print(data)
# print(data.datetime)
data = data \
.assign(tradetime=data['datetime'].apply(str), code=str(code)) \
.assign(datetime=pd.to_datetime(data['datetime'].apply(QA_util_future_to_realdatetime, 1))) \
.drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \
.assign(date=data['datetime'].apply(lambda x: str(x)[0:10])) \
.assign(date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(x))) \
.assign(time_stamp=data['datetime'].apply(lambda x: QA_util_time_stamp(x))) \
.assign(type=type_).set_index('datetime', drop=False, inplace=False)
return data.assign(datetime=data['datetime'].apply(lambda x: str(x)))[start:end].sort_index() | [
"期货数据",
"分钟线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1998-L2045 | [
"def",
"QA_fetch_get_future_min",
"(",
"code",
",",
"start",
",",
"end",
",",
"frequence",
"=",
"'1min'",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_extensionmarket_ip",
"(",
"ip",
",",
"port",
")",
"apix",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_future_transaction | 期货历史成交分笔 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_future_transaction(code, start, end, retry=4, ip=None, port=None):
'期货历史成交分笔'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
real_start, real_end = QA_util_get_real_datelist(start, end)
if real_start is None:
return None
real_id_range = []
with apix.connect(ip, port):
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
data = pd.DataFrame()
for index_ in range(trade_date_sse.index(real_start), trade_date_sse.index(real_end) + 1):
try:
data_ = __QA_fetch_get_future_transaction(
code, trade_date_sse[index_], retry, int(code_market.market), apix)
if len(data_) < 1:
return None
except Exception as e:
print(e)
QA_util_log_info('Wrong in Getting {} history transaction data in day {}'.format(
code, trade_date_sse[index_]))
else:
QA_util_log_info('Successfully Getting {} history transaction data in day {}'.format(
code, trade_date_sse[index_]))
data = data.append(data_)
if len(data) > 0:
return data.assign(datetime=data['datetime'].apply(lambda x: str(x)[0:19]))
else:
return None | def QA_fetch_get_future_transaction(code, start, end, retry=4, ip=None, port=None):
'期货历史成交分笔'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
real_start, real_end = QA_util_get_real_datelist(start, end)
if real_start is None:
return None
real_id_range = []
with apix.connect(ip, port):
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
data = pd.DataFrame()
for index_ in range(trade_date_sse.index(real_start), trade_date_sse.index(real_end) + 1):
try:
data_ = __QA_fetch_get_future_transaction(
code, trade_date_sse[index_], retry, int(code_market.market), apix)
if len(data_) < 1:
return None
except Exception as e:
print(e)
QA_util_log_info('Wrong in Getting {} history transaction data in day {}'.format(
code, trade_date_sse[index_]))
else:
QA_util_log_info('Successfully Getting {} history transaction data in day {}'.format(
code, trade_date_sse[index_]))
data = data.append(data_)
if len(data) > 0:
return data.assign(datetime=data['datetime'].apply(lambda x: str(x)[0:19]))
else:
return None | [
"期货历史成交分笔"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L2075-L2109 | [
"def",
"QA_fetch_get_future_transaction",
"(",
"code",
",",
"start",
",",
"end",
",",
"retry",
"=",
"4",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_extensionmarket_ip",
"(",
"ip",
",",
"port",
")",
"apix",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_future_transaction_realtime | 期货历史成交分笔 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_future_transaction_realtime(code, ip=None, port=None):
'期货历史成交分笔'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
with apix.connect(ip, port):
data = pd.DataFrame()
data = pd.concat([apix.to_df(apix.get_transaction_data(
int(code_market.market), code, (30 - i) * 1800)) for i in range(31)], axis=0)
return data.assign(datetime=pd.to_datetime(data['date'])).assign(date=lambda x: str(x)[0:10]) \
.assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False,
inplace=False) | def QA_fetch_get_future_transaction_realtime(code, ip=None, port=None):
'期货历史成交分笔'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
with apix.connect(ip, port):
data = pd.DataFrame()
data = pd.concat([apix.to_df(apix.get_transaction_data(
int(code_market.market), code, (30 - i) * 1800)) for i in range(31)], axis=0)
return data.assign(datetime=pd.to_datetime(data['date'])).assign(date=lambda x: str(x)[0:10]) \
.assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False,
inplace=False) | [
"期货历史成交分笔"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L2112-L2128 | [
"def",
"QA_fetch_get_future_transaction_realtime",
"(",
"code",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_extensionmarket_ip",
"(",
"ip",
",",
"port",
")",
"apix",
"=",
"TdxExHq_API",
"(",
")",
"global",
"exte... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_future_realtime | 期货实时价格 | QUANTAXIS/QAFetch/QATdx.py | def QA_fetch_get_future_realtime(code, ip=None, port=None):
'期货实时价格'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
__data = pd.DataFrame()
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
with apix.connect(ip, port):
__data = apix.to_df(apix.get_instrument_quote(
int(code_market.market), code))
__data['datetime'] = datetime.datetime.now()
# data = __data[['datetime', 'active1', 'active2', 'last_close', 'code', 'open', 'high', 'low', 'price', 'cur_vol',
# 's_vol', 'b_vol', 'vol', 'ask1', 'ask_vol1', 'bid1', 'bid_vol1', 'ask2', 'ask_vol2',
# 'bid2', 'bid_vol2', 'ask3', 'ask_vol3', 'bid3', 'bid_vol3', 'ask4',
# 'ask_vol4', 'bid4', 'bid_vol4', 'ask5', 'ask_vol5', 'bid5', 'bid_vol5']]
return __data.set_index(['datetime', 'code']) | def QA_fetch_get_future_realtime(code, ip=None, port=None):
'期货实时价格'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
global extension_market_list
extension_market_list = QA_fetch_get_extensionmarket_list(
) if extension_market_list is None else extension_market_list
__data = pd.DataFrame()
code_market = extension_market_list.query(
'code=="{}"'.format(code)).iloc[0]
with apix.connect(ip, port):
__data = apix.to_df(apix.get_instrument_quote(
int(code_market.market), code))
__data['datetime'] = datetime.datetime.now()
# data = __data[['datetime', 'active1', 'active2', 'last_close', 'code', 'open', 'high', 'low', 'price', 'cur_vol',
# 's_vol', 'b_vol', 'vol', 'ask1', 'ask_vol1', 'bid1', 'bid_vol1', 'ask2', 'ask_vol2',
# 'bid2', 'bid_vol2', 'ask3', 'ask_vol3', 'bid3', 'bid_vol3', 'ask4',
# 'ask_vol4', 'bid4', 'bid_vol4', 'ask5', 'ask_vol5', 'bid5', 'bid_vol5']]
return __data.set_index(['datetime', 'code']) | [
"期货实时价格"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L2131-L2150 | [
"def",
"QA_fetch_get_future_realtime",
"(",
"code",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_extensionmarket_ip",
"(",
"ip",
",",
"port",
")",
"apix",
"=",
"TdxExHq_API",
"(",
")",
"global",
"extension_market... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | concat | 类似于pd.concat 用于合并一个list里面的多个DataStruct,会自动去重
Arguments:
lists {[type]} -- [DataStruct1,DataStruct2,....,DataStructN]
Returns:
[type] -- new DataStruct | QUANTAXIS/QAData/dsmethods.py | def concat(lists):
"""类似于pd.concat 用于合并一个list里面的多个DataStruct,会自动去重
Arguments:
lists {[type]} -- [DataStruct1,DataStruct2,....,DataStructN]
Returns:
[type] -- new DataStruct
"""
return lists[0].new(
pd.concat([lists.data for lists in lists]).drop_duplicates()
) | def concat(lists):
"""类似于pd.concat 用于合并一个list里面的多个DataStruct,会自动去重
Arguments:
lists {[type]} -- [DataStruct1,DataStruct2,....,DataStructN]
Returns:
[type] -- new DataStruct
"""
return lists[0].new(
pd.concat([lists.data for lists in lists]).drop_duplicates()
) | [
"类似于pd",
".",
"concat",
"用于合并一个list里面的多个DataStruct",
"会自动去重"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/dsmethods.py#L39-L53 | [
"def",
"concat",
"(",
"lists",
")",
":",
"return",
"lists",
"[",
"0",
"]",
".",
"new",
"(",
"pd",
".",
"concat",
"(",
"[",
"lists",
".",
"data",
"for",
"lists",
"in",
"lists",
"]",
")",
".",
"drop_duplicates",
"(",
")",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | datastruct_formater | 一个任意格式转化为DataStruct的方法
Arguments:
data {[type]} -- [description]
Keyword Arguments:
frequence {[type]} -- [description] (default: {FREQUENCE.DAY})
market_type {[type]} -- [description] (default: {MARKET_TYPE.STOCK_CN})
default_header {list} -- [description] (default: {[]})
Returns:
[type] -- [description] | QUANTAXIS/QAData/dsmethods.py | def datastruct_formater(
data,
frequence=FREQUENCE.DAY,
market_type=MARKET_TYPE.STOCK_CN,
default_header=[]
):
"""一个任意格式转化为DataStruct的方法
Arguments:
data {[type]} -- [description]
Keyword Arguments:
frequence {[type]} -- [description] (default: {FREQUENCE.DAY})
market_type {[type]} -- [description] (default: {MARKET_TYPE.STOCK_CN})
default_header {list} -- [description] (default: {[]})
Returns:
[type] -- [description]
"""
if isinstance(data, list):
try:
res = pd.DataFrame(data, columns=default_header)
if frequence is FREQUENCE.DAY:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_day(
res.assign(date=pd.to_datetime(res.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
elif frequence in [FREQUENCE.ONE_MIN,
FREQUENCE.FIVE_MIN,
FREQUENCE.FIFTEEN_MIN,
FREQUENCE.THIRTY_MIN,
FREQUENCE.SIXTY_MIN]:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_min(
res.assign(datetime=pd.to_datetime(res.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
)
except:
pass
elif isinstance(data, np.ndarray):
try:
res = pd.DataFrame(data, columns=default_header)
if frequence is FREQUENCE.DAY:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_day(
res.assign(date=pd.to_datetime(res.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
elif frequence in [FREQUENCE.ONE_MIN,
FREQUENCE.FIVE_MIN,
FREQUENCE.FIFTEEN_MIN,
FREQUENCE.THIRTY_MIN,
FREQUENCE.SIXTY_MIN]:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_min(
res.assign(datetime=pd.to_datetime(res.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
)
except:
pass
elif isinstance(data, pd.DataFrame):
index = data.index
if isinstance(index, pd.MultiIndex):
pass
elif isinstance(index, pd.DatetimeIndex):
pass
elif isinstance(index, pd.Index):
pass | def datastruct_formater(
data,
frequence=FREQUENCE.DAY,
market_type=MARKET_TYPE.STOCK_CN,
default_header=[]
):
"""一个任意格式转化为DataStruct的方法
Arguments:
data {[type]} -- [description]
Keyword Arguments:
frequence {[type]} -- [description] (default: {FREQUENCE.DAY})
market_type {[type]} -- [description] (default: {MARKET_TYPE.STOCK_CN})
default_header {list} -- [description] (default: {[]})
Returns:
[type] -- [description]
"""
if isinstance(data, list):
try:
res = pd.DataFrame(data, columns=default_header)
if frequence is FREQUENCE.DAY:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_day(
res.assign(date=pd.to_datetime(res.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
elif frequence in [FREQUENCE.ONE_MIN,
FREQUENCE.FIVE_MIN,
FREQUENCE.FIFTEEN_MIN,
FREQUENCE.THIRTY_MIN,
FREQUENCE.SIXTY_MIN]:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_min(
res.assign(datetime=pd.to_datetime(res.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
)
except:
pass
elif isinstance(data, np.ndarray):
try:
res = pd.DataFrame(data, columns=default_header)
if frequence is FREQUENCE.DAY:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_day(
res.assign(date=pd.to_datetime(res.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
elif frequence in [FREQUENCE.ONE_MIN,
FREQUENCE.FIVE_MIN,
FREQUENCE.FIFTEEN_MIN,
FREQUENCE.THIRTY_MIN,
FREQUENCE.SIXTY_MIN]:
if market_type is MARKET_TYPE.STOCK_CN:
return QA_DataStruct_Stock_min(
res.assign(datetime=pd.to_datetime(res.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
)
except:
pass
elif isinstance(data, pd.DataFrame):
index = data.index
if isinstance(index, pd.MultiIndex):
pass
elif isinstance(index, pd.DatetimeIndex):
pass
elif isinstance(index, pd.Index):
pass | [
"一个任意格式转化为DataStruct的方法",
"Arguments",
":",
"data",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"Keyword",
"Arguments",
":",
"frequence",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"(",
"default",
":",
"{",
"FREQUENCE",
"."... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/dsmethods.py#L56-L138 | [
"def",
"datastruct_formater",
"(",
"data",
",",
"frequence",
"=",
"FREQUENCE",
".",
"DAY",
",",
"market_type",
"=",
"MARKET_TYPE",
".",
"STOCK_CN",
",",
"default_header",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"t... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | from_tushare | dataframe from tushare
Arguments:
dataframe {[type]} -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAData/dsmethods.py | def from_tushare(dataframe, dtype='day'):
"""dataframe from tushare
Arguments:
dataframe {[type]} -- [description]
Returns:
[type] -- [description]
"""
if dtype in ['day']:
return QA_DataStruct_Stock_day(
dataframe.assign(date=pd.to_datetime(dataframe.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
elif dtype in ['min']:
return QA_DataStruct_Stock_min(
dataframe.assign(datetime=pd.to_datetime(dataframe.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
) | def from_tushare(dataframe, dtype='day'):
"""dataframe from tushare
Arguments:
dataframe {[type]} -- [description]
Returns:
[type] -- [description]
"""
if dtype in ['day']:
return QA_DataStruct_Stock_day(
dataframe.assign(date=pd.to_datetime(dataframe.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
elif dtype in ['min']:
return QA_DataStruct_Stock_min(
dataframe.assign(datetime=pd.to_datetime(dataframe.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
) | [
"dataframe",
"from",
"tushare"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/dsmethods.py#L141-L166 | [
"def",
"from_tushare",
"(",
"dataframe",
",",
"dtype",
"=",
"'day'",
")",
":",
"if",
"dtype",
"in",
"[",
"'day'",
"]",
":",
"return",
"QA_DataStruct_Stock_day",
"(",
"dataframe",
".",
"assign",
"(",
"date",
"=",
"pd",
".",
"to_datetime",
"(",
"dataframe",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QDS_StockDayWarpper | 日线QDS装饰器 | QUANTAXIS/QAData/dsmethods.py | def QDS_StockDayWarpper(func):
"""
日线QDS装饰器
"""
def warpper(*args, **kwargs):
data = func(*args, **kwargs)
if isinstance(data.index, pd.MultiIndex):
return QA_DataStruct_Stock_day(data)
else:
return QA_DataStruct_Stock_day(
data.assign(date=pd.to_datetime(data.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
return warpper | def QDS_StockDayWarpper(func):
"""
日线QDS装饰器
"""
def warpper(*args, **kwargs):
data = func(*args, **kwargs)
if isinstance(data.index, pd.MultiIndex):
return QA_DataStruct_Stock_day(data)
else:
return QA_DataStruct_Stock_day(
data.assign(date=pd.to_datetime(data.date)
).set_index(['date',
'code'],
drop=False),
dtype='stock_day'
)
return warpper | [
"日线QDS装饰器"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/dsmethods.py#L169-L189 | [
"def",
"QDS_StockDayWarpper",
"(",
"func",
")",
":",
"def",
"warpper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"data",
".",
"index",
",",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QDS_StockMinWarpper | 分钟线QDS装饰器 | QUANTAXIS/QAData/dsmethods.py | def QDS_StockMinWarpper(func, *args, **kwargs):
"""
分钟线QDS装饰器
"""
def warpper(*args, **kwargs):
data = func(*args, **kwargs)
if isinstance(data.index, pd.MultiIndex):
return QA_DataStruct_Stock_min(data)
else:
return QA_DataStruct_Stock_min(
data.assign(datetime=pd.to_datetime(data.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
)
return warpper | def QDS_StockMinWarpper(func, *args, **kwargs):
"""
分钟线QDS装饰器
"""
def warpper(*args, **kwargs):
data = func(*args, **kwargs)
if isinstance(data.index, pd.MultiIndex):
return QA_DataStruct_Stock_min(data)
else:
return QA_DataStruct_Stock_min(
data.assign(datetime=pd.to_datetime(data.datetime)
).set_index(['datetime',
'code'],
drop=False),
dtype='stock_min'
)
return warpper | [
"分钟线QDS装饰器"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/dsmethods.py#L192-L211 | [
"def",
"QDS_StockMinWarpper",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"warpper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"i... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_get_stock_adj | 获取股票的复权因子
Arguments:
code {[type]} -- [description]
Keyword Arguments:
end {str} -- [description] (default: {''})
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QATushare.py | def QA_fetch_get_stock_adj(code, end=''):
"""获取股票的复权因子
Arguments:
code {[type]} -- [description]
Keyword Arguments:
end {str} -- [description] (default: {''})
Returns:
[type] -- [description]
"""
pro = get_pro()
adj = pro.adj_factor(ts_code=code, trade_date=end)
return adj | def QA_fetch_get_stock_adj(code, end=''):
"""获取股票的复权因子
Arguments:
code {[type]} -- [description]
Keyword Arguments:
end {str} -- [description] (default: {''})
Returns:
[type] -- [description]
"""
pro = get_pro()
adj = pro.adj_factor(ts_code=code, trade_date=end)
return adj | [
"获取股票的复权因子",
"Arguments",
":",
"code",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"Keyword",
"Arguments",
":",
"end",
"{",
"str",
"}",
"--",
"[",
"description",
"]",
"(",
"default",
":",
"{",
"}",
")",
"Returns",
":",
"[",
"type",
"... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATushare.py#L67-L82 | [
"def",
"QA_fetch_get_stock_adj",
"(",
"code",
",",
"end",
"=",
"''",
")",
":",
"pro",
"=",
"get_pro",
"(",
")",
"adj",
"=",
"pro",
".",
"adj_factor",
"(",
"ts_code",
"=",
"code",
",",
"trade_date",
"=",
"end",
")",
"return",
"adj"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | cover_time | 字符串 '20180101' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 20180101 ,长度8
:return: 类型float | QUANTAXIS/QAFetch/QATushare.py | def cover_time(date):
"""
字符串 '20180101' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 20180101 ,长度8
:return: 类型float
"""
datestr = str(date)[0:8]
date = time.mktime(time.strptime(datestr, '%Y%m%d'))
return date | def cover_time(date):
"""
字符串 '20180101' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 20180101 ,长度8
:return: 类型float
"""
datestr = str(date)[0:8]
date = time.mktime(time.strptime(datestr, '%Y%m%d'))
return date | [
"字符串",
"20180101",
"转变成",
"float",
"类型时间",
"类似",
"time",
".",
"time",
"()",
"返回的类型",
":",
"param",
"date",
":",
"字符串str",
"--",
"格式必须是",
"20180101",
",长度8",
":",
"return",
":",
"类型float"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATushare.py#L109-L117 | [
"def",
"cover_time",
"(",
"date",
")",
":",
"datestr",
"=",
"str",
"(",
"date",
")",
"[",
"0",
":",
"8",
"]",
"date",
"=",
"time",
".",
"mktime",
"(",
"time",
".",
"strptime",
"(",
"datestr",
",",
"'%Y%m%d'",
")",
")",
"return",
"date"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_block.new | 通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAData/QABlockStruct.py | def new(self, data):
"""通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description]
"""
temp = copy(self)
temp.__init__(data)
return temp | def new(self, data):
"""通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description]
"""
temp = copy(self)
temp.__init__(data)
return temp | [
"通过data新建一个stock_block"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QABlockStruct.py#L50-L61 | [
"def",
"new",
"(",
"self",
",",
"data",
")",
":",
"temp",
"=",
"copy",
"(",
"self",
")",
"temp",
".",
"__init__",
"(",
"data",
")",
"return",
"temp"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_block.view_code | 按股票排列的查看blockname的视图
Returns:
[type] -- [description] | QUANTAXIS/QAData/QABlockStruct.py | def view_code(self):
"""按股票排列的查看blockname的视图
Returns:
[type] -- [description]
"""
return self.data.groupby(level=1).apply(
lambda x:
[item for item in x.index.remove_unused_levels().levels[0]]
) | def view_code(self):
"""按股票排列的查看blockname的视图
Returns:
[type] -- [description]
"""
return self.data.groupby(level=1).apply(
lambda x:
[item for item in x.index.remove_unused_levels().levels[0]]
) | [
"按股票排列的查看blockname的视图"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QABlockStruct.py#L94-L104 | [
"def",
"view_code",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"[",
"item",
"for",
"item",
"in",
"x",
".",
"index",
".",
"remove_unused_levels",
"(",
")"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_block.get_code | getcode 获取某一只股票的板块
Arguments:
code {str} -- 股票代码
Returns:
DataStruct -- [description] | QUANTAXIS/QAData/QABlockStruct.py | def get_code(self, code):
"""getcode 获取某一只股票的板块
Arguments:
code {str} -- 股票代码
Returns:
DataStruct -- [description]
"""
# code= [code] if isinstance(code,str) else
return self.new(self.data.loc[(slice(None), code), :]) | def get_code(self, code):
"""getcode 获取某一只股票的板块
Arguments:
code {str} -- 股票代码
Returns:
DataStruct -- [description]
"""
# code= [code] if isinstance(code,str) else
return self.new(self.data.loc[(slice(None), code), :]) | [
"getcode",
"获取某一只股票的板块"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QABlockStruct.py#L128-L138 | [
"def",
"get_code",
"(",
"self",
",",
"code",
")",
":",
"# code= [code] if isinstance(code,str) else",
"return",
"self",
".",
"new",
"(",
"self",
".",
"data",
".",
"loc",
"[",
"(",
"slice",
"(",
"None",
")",
",",
"code",
")",
",",
":",
"]",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_block.get_block | getblock 获取板块, block_name是list或者是单个str
Arguments:
block_name {[type]} -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAData/QABlockStruct.py | def get_block(self, block_name):
"""getblock 获取板块, block_name是list或者是单个str
Arguments:
block_name {[type]} -- [description]
Returns:
[type] -- [description]
"""
# block_name = [block_name] if isinstance(
# block_name, str) else block_name
# return QA_DataStruct_Stock_block(self.data[self.data.blockname.apply(lambda x: x in block_name)])
return self.new(self.data.loc[(block_name, slice(None)), :]) | def get_block(self, block_name):
"""getblock 获取板块, block_name是list或者是单个str
Arguments:
block_name {[type]} -- [description]
Returns:
[type] -- [description]
"""
# block_name = [block_name] if isinstance(
# block_name, str) else block_name
# return QA_DataStruct_Stock_block(self.data[self.data.blockname.apply(lambda x: x in block_name)])
return self.new(self.data.loc[(block_name, slice(None)), :]) | [
"getblock",
"获取板块",
"block_name是list或者是单个str"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QABlockStruct.py#L140-L153 | [
"def",
"get_block",
"(",
"self",
",",
"block_name",
")",
":",
"# block_name = [block_name] if isinstance(",
"# block_name, str) else block_name",
"# return QA_DataStruct_Stock_block(self.data[self.data.blockname.apply(lambda x: x in block_name)])",
"return",
"self",
".",
"new",
"("... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_DataStruct_Stock_block.get_both_code | get_both_code 获取几个股票相同的版块
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description] | QUANTAXIS/QAData/QABlockStruct.py | def get_both_code(self, code):
"""get_both_code 获取几个股票相同的版块
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description]
"""
return self.new(self.data.loc[(slice(None), code), :]) | def get_both_code(self, code):
"""get_both_code 获取几个股票相同的版块
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description]
"""
return self.new(self.data.loc[(slice(None), code), :]) | [
"get_both_code",
"获取几个股票相同的版块",
"Arguments",
":",
"code",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"Returns",
":",
"[",
"type",
"]",
"--",
"[",
"description",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QABlockStruct.py#L155-L165 | [
"def",
"get_both_code",
"(",
"self",
",",
"code",
")",
":",
"return",
"self",
".",
"new",
"(",
"self",
".",
"data",
".",
"loc",
"[",
"(",
"slice",
"(",
"None",
")",
",",
"code",
")",
",",
":",
"]",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_get_tick | 统一的获取期货/股票tick的接口 | QUANTAXIS/QAFetch/Fetcher.py | def QA_get_tick(code, start, end, market):
"""
统一的获取期货/股票tick的接口
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
res = QATdx.QA_fetch_get_stock_transaction(code, start, end)
elif market == MARKET_TYPE.FUTURE_CN:
res = QATdx.QA_fetch_get_future_transaction(code, start, end)
return res | def QA_get_tick(code, start, end, market):
"""
统一的获取期货/股票tick的接口
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
res = QATdx.QA_fetch_get_stock_transaction(code, start, end)
elif market == MARKET_TYPE.FUTURE_CN:
res = QATdx.QA_fetch_get_future_transaction(code, start, end)
return res | [
"统一的获取期货",
"/",
"股票tick的接口"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/Fetcher.py#L93-L102 | [
"def",
"QA_get_tick",
"(",
"code",
",",
"start",
",",
"end",
",",
"market",
")",
":",
"res",
"=",
"None",
"if",
"market",
"==",
"MARKET_TYPE",
".",
"STOCK_CN",
":",
"res",
"=",
"QATdx",
".",
"QA_fetch_get_stock_transaction",
"(",
"code",
",",
"start",
",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_get_realtime | 统一的获取期货/股票实时行情的接口 | QUANTAXIS/QAFetch/Fetcher.py | def QA_get_realtime(code, market):
"""
统一的获取期货/股票实时行情的接口
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
res = QATdx.QA_fetch_get_stock_realtime(code)
elif market == MARKET_TYPE.FUTURE_CN:
res = QATdx.QA_fetch_get_future_realtime(code)
return res | def QA_get_realtime(code, market):
"""
统一的获取期货/股票实时行情的接口
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
res = QATdx.QA_fetch_get_stock_realtime(code)
elif market == MARKET_TYPE.FUTURE_CN:
res = QATdx.QA_fetch_get_future_realtime(code)
return res | [
"统一的获取期货",
"/",
"股票实时行情的接口"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/Fetcher.py#L105-L115 | [
"def",
"QA_get_realtime",
"(",
"code",
",",
"market",
")",
":",
"res",
"=",
"None",
"if",
"market",
"==",
"MARKET_TYPE",
".",
"STOCK_CN",
":",
"res",
"=",
"QATdx",
".",
"QA_fetch_get_stock_realtime",
"(",
"code",
")",
"elif",
"market",
"==",
"MARKET_TYPE",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_quotation | 一个统一的获取k线的方法
如果使用mongo,从本地数据库获取,失败则在线获取
Arguments:
code {str/list} -- 期货/股票的代码
start {str} -- 开始日期
end {str} -- 结束日期
frequence {enum} -- 频率 QA.FREQUENCE
market {enum} -- 市场 QA.MARKET_TYPE
source {enum} -- 来源 QA.DATASOURCE
output {enum} -- 输出类型 QA.OUTPUT_FORMAT | QUANTAXIS/QAFetch/Fetcher.py | def QA_quotation(code, start, end, frequence, market, source=DATASOURCE.TDX, output=OUTPUT_FORMAT.DATAFRAME):
"""一个统一的获取k线的方法
如果使用mongo,从本地数据库获取,失败则在线获取
Arguments:
code {str/list} -- 期货/股票的代码
start {str} -- 开始日期
end {str} -- 结束日期
frequence {enum} -- 频率 QA.FREQUENCE
market {enum} -- 市场 QA.MARKET_TYPE
source {enum} -- 来源 QA.DATASOURCE
output {enum} -- 输出类型 QA.OUTPUT_FORMAT
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
if frequence == FREQUENCE.DAY:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_stock_day_adv(code, start, end)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_stock_day(code, start, end, '00')
res = QA_DataStruct_Stock_day(res.set_index(['date', 'code']))
elif source == DATASOURCE.TUSHARE:
res = QATushare.QA_fetch_get_stock_day(code, start, end, '00')
elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_stock_min_adv(
code, start, end, frequence=frequence)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_stock_min(
code, start, end, frequence=frequence)
res = QA_DataStruct_Stock_min(
res.set_index(['datetime', 'code']))
elif market == MARKET_TYPE.FUTURE_CN:
if frequence == FREQUENCE.DAY:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_future_day_adv(code, start, end)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_future_day(code, start, end)
res = QA_DataStruct_Future_day(res.set_index(['date', 'code']))
elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_future_min_adv(
code, start, end, frequence=frequence)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_future_min(
code, start, end, frequence=frequence)
res = QA_DataStruct_Future_min(
res.set_index(['datetime', 'code']))
# 指数代码和股票代码是冲突重复的, sh000001 上证指数 000001 是不同的
elif market == MARKET_TYPE.INDEX_CN:
if frequence == FREQUENCE.DAY:
if source == DATASOURCE.MONGO:
res = QAQueryAdv.QA_fetch_index_day_adv(code, start, end)
elif market == MARKET_TYPE.OPTION_CN:
if source == DATASOURCE.MONGO:
#res = QAQueryAdv.QA_fetch_option_day_adv(code, start, end)
raise NotImplementedError('CURRENT NOT FINISH THIS METHOD')
# print(type(res))
if output is OUTPUT_FORMAT.DATAFRAME:
return res.data
elif output is OUTPUT_FORMAT.DATASTRUCT:
return res
elif output is OUTPUT_FORMAT.NDARRAY:
return res.to_numpy()
elif output is OUTPUT_FORMAT.JSON:
return res.to_json()
elif output is OUTPUT_FORMAT.LIST:
return res.to_list() | def QA_quotation(code, start, end, frequence, market, source=DATASOURCE.TDX, output=OUTPUT_FORMAT.DATAFRAME):
"""一个统一的获取k线的方法
如果使用mongo,从本地数据库获取,失败则在线获取
Arguments:
code {str/list} -- 期货/股票的代码
start {str} -- 开始日期
end {str} -- 结束日期
frequence {enum} -- 频率 QA.FREQUENCE
market {enum} -- 市场 QA.MARKET_TYPE
source {enum} -- 来源 QA.DATASOURCE
output {enum} -- 输出类型 QA.OUTPUT_FORMAT
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
if frequence == FREQUENCE.DAY:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_stock_day_adv(code, start, end)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_stock_day(code, start, end, '00')
res = QA_DataStruct_Stock_day(res.set_index(['date', 'code']))
elif source == DATASOURCE.TUSHARE:
res = QATushare.QA_fetch_get_stock_day(code, start, end, '00')
elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_stock_min_adv(
code, start, end, frequence=frequence)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_stock_min(
code, start, end, frequence=frequence)
res = QA_DataStruct_Stock_min(
res.set_index(['datetime', 'code']))
elif market == MARKET_TYPE.FUTURE_CN:
if frequence == FREQUENCE.DAY:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_future_day_adv(code, start, end)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_future_day(code, start, end)
res = QA_DataStruct_Future_day(res.set_index(['date', 'code']))
elif frequence in [FREQUENCE.ONE_MIN, FREQUENCE.FIVE_MIN, FREQUENCE.FIFTEEN_MIN, FREQUENCE.THIRTY_MIN, FREQUENCE.SIXTY_MIN]:
if source == DATASOURCE.MONGO:
try:
res = QAQueryAdv.QA_fetch_future_min_adv(
code, start, end, frequence=frequence)
except:
res = None
if source == DATASOURCE.TDX or res == None:
res = QATdx.QA_fetch_get_future_min(
code, start, end, frequence=frequence)
res = QA_DataStruct_Future_min(
res.set_index(['datetime', 'code']))
# 指数代码和股票代码是冲突重复的, sh000001 上证指数 000001 是不同的
elif market == MARKET_TYPE.INDEX_CN:
if frequence == FREQUENCE.DAY:
if source == DATASOURCE.MONGO:
res = QAQueryAdv.QA_fetch_index_day_adv(code, start, end)
elif market == MARKET_TYPE.OPTION_CN:
if source == DATASOURCE.MONGO:
#res = QAQueryAdv.QA_fetch_option_day_adv(code, start, end)
raise NotImplementedError('CURRENT NOT FINISH THIS METHOD')
# print(type(res))
if output is OUTPUT_FORMAT.DATAFRAME:
return res.data
elif output is OUTPUT_FORMAT.DATASTRUCT:
return res
elif output is OUTPUT_FORMAT.NDARRAY:
return res.to_numpy()
elif output is OUTPUT_FORMAT.JSON:
return res.to_json()
elif output is OUTPUT_FORMAT.LIST:
return res.to_list() | [
"一个统一的获取k线的方法",
"如果使用mongo",
"从本地数据库获取",
"失败则在线获取"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/Fetcher.py#L118-L201 | [
"def",
"QA_quotation",
"(",
"code",
",",
"start",
",",
"end",
",",
"frequence",
",",
"market",
",",
"source",
"=",
"DATASOURCE",
".",
"TDX",
",",
"output",
"=",
"OUTPUT_FORMAT",
".",
"DATAFRAME",
")",
":",
"res",
"=",
"None",
"if",
"market",
"==",
"MAR... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_random_with_zh_stock_code | 随机生成股票代码
:param stockNumber: 生成个数
:return: ['60XXXX', '00XXXX', '300XXX'] | QUANTAXIS/QAUtil/QARandom.py | def QA_util_random_with_zh_stock_code(stockNumber=10):
'''
随机生成股票代码
:param stockNumber: 生成个数
:return: ['60XXXX', '00XXXX', '300XXX']
'''
codeList = []
pt = 0
for i in range(stockNumber):
if pt == 0:
#print("random 60XXXX")
iCode = random.randint(600000, 609999)
aCode = "%06d" % iCode
elif pt == 1:
#print("random 00XXXX")
iCode = random.randint(600000, 600999)
aCode = "%06d" % iCode
elif pt == 2:
#print("random 00XXXX")
iCode = random.randint(2000, 9999)
aCode = "%06d" % iCode
elif pt == 3:
#print("random 300XXX")
iCode = random.randint(300000, 300999)
aCode = "%06d" % iCode
elif pt == 4:
#print("random 00XXXX")
iCode = random.randint(2000, 2999)
aCode = "%06d" % iCode
pt = (pt + 1) % 5
codeList.append(aCode)
return codeList | def QA_util_random_with_zh_stock_code(stockNumber=10):
'''
随机生成股票代码
:param stockNumber: 生成个数
:return: ['60XXXX', '00XXXX', '300XXX']
'''
codeList = []
pt = 0
for i in range(stockNumber):
if pt == 0:
#print("random 60XXXX")
iCode = random.randint(600000, 609999)
aCode = "%06d" % iCode
elif pt == 1:
#print("random 00XXXX")
iCode = random.randint(600000, 600999)
aCode = "%06d" % iCode
elif pt == 2:
#print("random 00XXXX")
iCode = random.randint(2000, 9999)
aCode = "%06d" % iCode
elif pt == 3:
#print("random 300XXX")
iCode = random.randint(300000, 300999)
aCode = "%06d" % iCode
elif pt == 4:
#print("random 00XXXX")
iCode = random.randint(2000, 2999)
aCode = "%06d" % iCode
pt = (pt + 1) % 5
codeList.append(aCode)
return codeList | [
"随机生成股票代码",
":",
"param",
"stockNumber",
":",
"生成个数",
":",
"return",
":",
"[",
"60XXXX",
"00XXXX",
"300XXX",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QARandom.py#L28-L63 | [
"def",
"QA_util_random_with_zh_stock_code",
"(",
"stockNumber",
"=",
"10",
")",
":",
"codeList",
"=",
"[",
"]",
"pt",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"stockNumber",
")",
":",
"if",
"pt",
"==",
"0",
":",
"#print(\"random 60XXXX\")",
"iCode",
"=",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_util_random_with_topic | 生成account随机值
Acc+4数字id+4位大小写随机 | QUANTAXIS/QAUtil/QARandom.py | def QA_util_random_with_topic(topic='Acc', lens=8):
"""
生成account随机值
Acc+4数字id+4位大小写随机
"""
_list = [chr(i) for i in range(65,
91)] + [chr(i) for i in range(97,
123)
] + [str(i) for i in range(10)]
num = random.sample(_list, lens)
return '{}_{}'.format(topic, ''.join(num)) | def QA_util_random_with_topic(topic='Acc', lens=8):
"""
生成account随机值
Acc+4数字id+4位大小写随机
"""
_list = [chr(i) for i in range(65,
91)] + [chr(i) for i in range(97,
123)
] + [str(i) for i in range(10)]
num = random.sample(_list, lens)
return '{}_{}'.format(topic, ''.join(num)) | [
"生成account随机值"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAUtil/QARandom.py#L66-L79 | [
"def",
"QA_util_random_with_topic",
"(",
"topic",
"=",
"'Acc'",
",",
"lens",
"=",
"8",
")",
":",
"_list",
"=",
"[",
"chr",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"65",
",",
"91",
")",
"]",
"+",
"[",
"chr",
"(",
"i",
")",
"for",
"i",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_Position.update_pos | 支持股票/期货的更新仓位
Arguments:
price {[type]} -- [description]
amount {[type]} -- [description]
towards {[type]} -- [description]
margin: 30080
margin_long: 0
margin_short: 30080
open_cost_long: 0
open_cost_short: 419100
open_price_long: 4193
open_price_short: 4191
position_cost_long: 0
position_cost_short: 419100
position_price_long: 4193
position_price_short: 4191
position_profit: -200
position_profit_long: 0
position_profit_short: -200 | QUANTAXIS/QAMarket/QAPosition.py | def update_pos(self, price, amount, towards):
"""支持股票/期货的更新仓位
Arguments:
price {[type]} -- [description]
amount {[type]} -- [description]
towards {[type]} -- [description]
margin: 30080
margin_long: 0
margin_short: 30080
open_cost_long: 0
open_cost_short: 419100
open_price_long: 4193
open_price_short: 4191
position_cost_long: 0
position_cost_short: 419100
position_price_long: 4193
position_price_short: 4191
position_profit: -200
position_profit_long: 0
position_profit_short: -200
"""
temp_cost = amount*price * \
self.market_preset.get('unit_table', 1)
# if towards == ORDER_DIRECTION.SELL_CLOSE:
if towards == ORDER_DIRECTION.BUY:
# 股票模式/ 期货买入开仓
self.volume_long_today += amount
elif towards == ORDER_DIRECTION.SELL:
# 股票卖出模式:
# 今日买入仓位不能卖出
if self.volume_long_his > amount:
self.volume_long_his -= amount
elif towards == ORDER_DIRECTION.BUY_OPEN:
# 增加保证金
self.margin_long += temp_cost * \
self.market_preset['buy_frozen_coeff']
# 重算开仓均价
self.open_price_long = (
self.open_price_long * self.volume_long + amount*price) / (amount + self.volume_long)
# 重算持仓均价
self.position_price_long = (
self.position_price_long * self.volume_long + amount * price) / (amount + self.volume_long)
# 增加今仓数量 ==> 会自动增加volume_long
self.volume_long_today += amount
#
self.open_cost_long += temp_cost
elif towards == ORDER_DIRECTION.SELL_OPEN:
# 增加保证金
self.margin_short += temp_cost * \
self.market_preset['sell_frozen_coeff']
# 重新计算开仓/持仓成本
self.open_price_short = (
self.open_price_short * self.volume_short + amount*price) / (amount + self.volume_short)
self.position_price_short = (
self.position_price_short * self.volume_short + amount * price) / (amount + self.volume_short)
self.open_cost_short += temp_cost
self.volume_short_today += amount
elif towards == ORDER_DIRECTION.BUY_CLOSETODAY:
if self.volume_short_today > amount:
self.position_cost_short = self.position_cost_short * \
(self.volume_short-amount)/self.volume_short
self.open_cost_short = self.open_cost_short * \
(self.volume_short-amount)/self.volume_short
self.volume_short_today -= amount
# close_profit = (self.position_price_short - price) * volume * position->ins->volume_multiple;
#self.volume_short_frozen_today += amount
# 释放保证金
# TODO
# self.margin_short
#self.open_cost_short = price* amount
elif towards == ORDER_DIRECTION.SELL_CLOSETODAY:
if self.volume_long_today > amount:
self.position_cost_long = self.position_cost_long * \
(self.volume_long - amount)/self.volume_long
self.open_cost_long = self.open_cost_long * \
(self.volume_long-amount)/self.volume_long
self.volume_long_today -= amount
elif towards == ORDER_DIRECTION.BUY_CLOSE:
# 有昨仓先平昨仓
self.position_cost_short = self.position_cost_short * \
(self.volume_short-amount)/self.volume_short
self.open_cost_short = self.open_cost_short * \
(self.volume_short-amount)/self.volume_short
if self.volume_short_his >= amount:
self.volume_short_his -= amount
else:
self.volume_short_today -= (amount - self.volume_short_his)
self.volume_short_his = 0
elif towards == ORDER_DIRECTION.SELL_CLOSE:
# 有昨仓先平昨仓
self.position_cost_long = self.position_cost_long * \
(self.volume_long - amount)/self.volume_long
self.open_cost_long = self.open_cost_long * \
(self.volume_long-amount)/self.volume_long
if self.volume_long_his >= amount:
self.volume_long_his -= amount
else:
self.volume_long_today -= (amount - self.volume_long_his)
self.volume_long_his -= amount | def update_pos(self, price, amount, towards):
"""支持股票/期货的更新仓位
Arguments:
price {[type]} -- [description]
amount {[type]} -- [description]
towards {[type]} -- [description]
margin: 30080
margin_long: 0
margin_short: 30080
open_cost_long: 0
open_cost_short: 419100
open_price_long: 4193
open_price_short: 4191
position_cost_long: 0
position_cost_short: 419100
position_price_long: 4193
position_price_short: 4191
position_profit: -200
position_profit_long: 0
position_profit_short: -200
"""
temp_cost = amount*price * \
self.market_preset.get('unit_table', 1)
# if towards == ORDER_DIRECTION.SELL_CLOSE:
if towards == ORDER_DIRECTION.BUY:
# 股票模式/ 期货买入开仓
self.volume_long_today += amount
elif towards == ORDER_DIRECTION.SELL:
# 股票卖出模式:
# 今日买入仓位不能卖出
if self.volume_long_his > amount:
self.volume_long_his -= amount
elif towards == ORDER_DIRECTION.BUY_OPEN:
# 增加保证金
self.margin_long += temp_cost * \
self.market_preset['buy_frozen_coeff']
# 重算开仓均价
self.open_price_long = (
self.open_price_long * self.volume_long + amount*price) / (amount + self.volume_long)
# 重算持仓均价
self.position_price_long = (
self.position_price_long * self.volume_long + amount * price) / (amount + self.volume_long)
# 增加今仓数量 ==> 会自动增加volume_long
self.volume_long_today += amount
#
self.open_cost_long += temp_cost
elif towards == ORDER_DIRECTION.SELL_OPEN:
# 增加保证金
self.margin_short += temp_cost * \
self.market_preset['sell_frozen_coeff']
# 重新计算开仓/持仓成本
self.open_price_short = (
self.open_price_short * self.volume_short + amount*price) / (amount + self.volume_short)
self.position_price_short = (
self.position_price_short * self.volume_short + amount * price) / (amount + self.volume_short)
self.open_cost_short += temp_cost
self.volume_short_today += amount
elif towards == ORDER_DIRECTION.BUY_CLOSETODAY:
if self.volume_short_today > amount:
self.position_cost_short = self.position_cost_short * \
(self.volume_short-amount)/self.volume_short
self.open_cost_short = self.open_cost_short * \
(self.volume_short-amount)/self.volume_short
self.volume_short_today -= amount
# close_profit = (self.position_price_short - price) * volume * position->ins->volume_multiple;
#self.volume_short_frozen_today += amount
# 释放保证金
# TODO
# self.margin_short
#self.open_cost_short = price* amount
elif towards == ORDER_DIRECTION.SELL_CLOSETODAY:
if self.volume_long_today > amount:
self.position_cost_long = self.position_cost_long * \
(self.volume_long - amount)/self.volume_long
self.open_cost_long = self.open_cost_long * \
(self.volume_long-amount)/self.volume_long
self.volume_long_today -= amount
elif towards == ORDER_DIRECTION.BUY_CLOSE:
# 有昨仓先平昨仓
self.position_cost_short = self.position_cost_short * \
(self.volume_short-amount)/self.volume_short
self.open_cost_short = self.open_cost_short * \
(self.volume_short-amount)/self.volume_short
if self.volume_short_his >= amount:
self.volume_short_his -= amount
else:
self.volume_short_today -= (amount - self.volume_short_his)
self.volume_short_his = 0
elif towards == ORDER_DIRECTION.SELL_CLOSE:
# 有昨仓先平昨仓
self.position_cost_long = self.position_cost_long * \
(self.volume_long - amount)/self.volume_long
self.open_cost_long = self.open_cost_long * \
(self.volume_long-amount)/self.volume_long
if self.volume_long_his >= amount:
self.volume_long_his -= amount
else:
self.volume_long_today -= (amount - self.volume_long_his)
self.volume_long_his -= amount | [
"支持股票",
"/",
"期货的更新仓位"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAPosition.py#L265-L373 | [
"def",
"update_pos",
"(",
"self",
",",
"price",
",",
"amount",
",",
"towards",
")",
":",
"temp_cost",
"=",
"amount",
"*",
"price",
"*",
"self",
".",
"market_preset",
".",
"get",
"(",
"'unit_table'",
",",
"1",
")",
"# if towards == ORDER_DIRECTION.SELL_CLOSE:",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_Position.settle | 收盘后的结算事件 | QUANTAXIS/QAMarket/QAPosition.py | def settle(self):
"""收盘后的结算事件
"""
self.volume_long_his += self.volume_long_today
self.volume_long_today = 0
self.volume_long_frozen_today = 0
self.volume_short_his += self.volume_short_today
self.volume_short_today = 0
self.volume_short_frozen_today = 0 | def settle(self):
"""收盘后的结算事件
"""
self.volume_long_his += self.volume_long_today
self.volume_long_today = 0
self.volume_long_frozen_today = 0
self.volume_short_his += self.volume_short_today
self.volume_short_today = 0
self.volume_short_frozen_today = 0 | [
"收盘后的结算事件"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAPosition.py#L377-L385 | [
"def",
"settle",
"(",
"self",
")",
":",
"self",
".",
"volume_long_his",
"+=",
"self",
".",
"volume_long_today",
"self",
".",
"volume_long_today",
"=",
"0",
"self",
".",
"volume_long_frozen_today",
"=",
"0",
"self",
".",
"volume_short_his",
"+=",
"self",
".",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_Position.close_available | 可平仓数量
Returns:
[type] -- [description] | QUANTAXIS/QAMarket/QAPosition.py | def close_available(self):
"""可平仓数量
Returns:
[type] -- [description]
"""
return {
'volume_long': self.volume_long - self.volume_long_frozen,
'volume_short': self.volume_short - self.volume_short_frozen
} | def close_available(self):
"""可平仓数量
Returns:
[type] -- [description]
"""
return {
'volume_long': self.volume_long - self.volume_long_frozen,
'volume_short': self.volume_short - self.volume_short_frozen
} | [
"可平仓数量"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAPosition.py#L395-L404 | [
"def",
"close_available",
"(",
"self",
")",
":",
"return",
"{",
"'volume_long'",
":",
"self",
".",
"volume_long",
"-",
"self",
".",
"volume_long_frozen",
",",
"'volume_short'",
":",
"self",
".",
"volume_short",
"-",
"self",
".",
"volume_short_frozen",
"}"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_PMS.orderAction | 委托回报 | QUANTAXIS/QAMarket/QAPosition.py | def orderAction(self, order:QA_Order):
"""
委托回报
"""
return self.pms[order.code][order.order_id].receive_order(order) | def orderAction(self, order:QA_Order):
"""
委托回报
"""
return self.pms[order.code][order.order_id].receive_order(order) | [
"委托回报"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAMarket/QAPosition.py#L464-L468 | [
"def",
"orderAction",
"(",
"self",
",",
"order",
":",
"QA_Order",
")",
":",
"return",
"self",
".",
"pms",
"[",
"order",
".",
"code",
"]",
"[",
"order",
".",
"order_id",
"]",
".",
"receive_order",
"(",
"order",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_min | 聚宽实现方式
save current day's stock_min data | QUANTAXIS/QASU/save_jq.py | def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
"""
聚宽实现方式
save current day's stock_min data
"""
# 导入聚宽模块且进行登录
try:
import jqdatasdk
# 请自行将 JQUSERNAME 和 JQUSERPASSWD 修改为自己的账号密码
jqdatasdk.auth("JQUSERNAME", "JQUSERPASSWD")
except:
raise ModuleNotFoundError
# 股票代码格式化
code_list = list(
map(
lambda x: x + ".XSHG" if x[0] == "6" else x + ".XSHE",
QA_fetch_get_stock_list().code.unique().tolist(),
))
coll = client.stock_min
coll.create_index([
("code", pymongo.ASCENDING),
("time_stamp", pymongo.ASCENDING),
("date_stamp", pymongo.ASCENDING),
])
err = []
def __transform_jq_to_qa(df, code, type_):
"""
处理 jqdata 分钟数据为 qa 格式,并存入数据库
1. jdatasdk 数据格式:
open close high low volume money
2018-12-03 09:31:00 10.59 10.61 10.61 10.59 8339100.0 88377836.0
2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配,具体处理详见相应源码
open close high low vol amount ...
datetime
2018-12-03 09:31:00 10.99 10.90 10.99 10.90 2.211700e+06 2.425626e+07 ...
"""
if df is None or len(df) == 0:
raise ValueError("没有聚宽数据")
df = df.reset_index().rename(columns={
"index": "datetime",
"volume": "vol",
"money": "amount"
})
df["code"] = code
df["date"] = df.datetime.map(str).str.slice(0, 10)
df = df.set_index("datetime", drop=False)
df["date_stamp"] = df["date"].apply(lambda x: QA_util_date_stamp(x))
df["time_stamp"] = (
df["datetime"].map(str).apply(lambda x: QA_util_time_stamp(x)))
df["type"] = type_
return df[[
"open",
"close",
"high",
"low",
"vol",
"amount",
"datetime",
"code",
"date",
"date_stamp",
"time_stamp",
"type",
]]
def __saving_work(code, coll):
QA_util_log_info(
"##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
try:
for type_ in ["1min", "5min", "15min", "30min", "60min"]:
col_filter = {"code": str(code)[0:6], "type": type_}
ref_ = coll.find(col_filter)
end_time = str(now_time())[0:19]
if coll.count_documents(col_filter) > 0:
start_time = ref_[coll.count_documents(
col_filter) - 1]["datetime"]
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"].index(type_),
str(code)[0:6],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = jqdatasdk.get_price(
security=code,
start_date=start_time,
end_date=end_time,
frequency=type_.split("min")[0]+"m",
)
__data = __transform_jq_to_qa(
df, code=code[:6], type_=type_)
if len(__data) > 1:
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
else:
start_time = "2015-01-01 09:30:00"
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"].index(type_),
str(code)[0:6],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
__data == __transform_jq_to_qa(
jqdatasdk.get_price(
security=code,
start_date=start_time,
end_date=end_time,
frequency=type_.split("min")[0]+"m",
),
code=code[:6],
type_=type_
)
if len(__data) > 1:
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
except Exception as e:
QA_util_log_info(e, ui_log=ui_log)
err.append(code)
QA_util_log_info(err, ui_log=ui_log)
# 聚宽之多允许三个线程连接
executor = ThreadPoolExecutor(max_workers=2)
res = {
executor.submit(__saving_work, code_list[i_], coll)
for i_ in range(len(code_list))
}
count = 0
for i_ in concurrent.futures.as_completed(res):
QA_util_log_info(
'The {} of Total {}'.format(count,
len(code_list)),
ui_log=ui_log
)
strProgress = "DOWNLOAD PROGRESS {} ".format(
str(float(count / len(code_list) * 100))[0:4] + "%")
intProgress = int(count / len(code_list) * 10000.0)
QA_util_log_info(
strProgress,
ui_log,
ui_progress=ui_progress,
ui_progress_int_value=intProgress
)
count = count + 1
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log) | def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
"""
聚宽实现方式
save current day's stock_min data
"""
# 导入聚宽模块且进行登录
try:
import jqdatasdk
# 请自行将 JQUSERNAME 和 JQUSERPASSWD 修改为自己的账号密码
jqdatasdk.auth("JQUSERNAME", "JQUSERPASSWD")
except:
raise ModuleNotFoundError
# 股票代码格式化
code_list = list(
map(
lambda x: x + ".XSHG" if x[0] == "6" else x + ".XSHE",
QA_fetch_get_stock_list().code.unique().tolist(),
))
coll = client.stock_min
coll.create_index([
("code", pymongo.ASCENDING),
("time_stamp", pymongo.ASCENDING),
("date_stamp", pymongo.ASCENDING),
])
err = []
def __transform_jq_to_qa(df, code, type_):
"""
处理 jqdata 分钟数据为 qa 格式,并存入数据库
1. jdatasdk 数据格式:
open close high low volume money
2018-12-03 09:31:00 10.59 10.61 10.61 10.59 8339100.0 88377836.0
2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配,具体处理详见相应源码
open close high low vol amount ...
datetime
2018-12-03 09:31:00 10.99 10.90 10.99 10.90 2.211700e+06 2.425626e+07 ...
"""
if df is None or len(df) == 0:
raise ValueError("没有聚宽数据")
df = df.reset_index().rename(columns={
"index": "datetime",
"volume": "vol",
"money": "amount"
})
df["code"] = code
df["date"] = df.datetime.map(str).str.slice(0, 10)
df = df.set_index("datetime", drop=False)
df["date_stamp"] = df["date"].apply(lambda x: QA_util_date_stamp(x))
df["time_stamp"] = (
df["datetime"].map(str).apply(lambda x: QA_util_time_stamp(x)))
df["type"] = type_
return df[[
"open",
"close",
"high",
"low",
"vol",
"amount",
"datetime",
"code",
"date",
"date_stamp",
"time_stamp",
"type",
]]
def __saving_work(code, coll):
QA_util_log_info(
"##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
try:
for type_ in ["1min", "5min", "15min", "30min", "60min"]:
col_filter = {"code": str(code)[0:6], "type": type_}
ref_ = coll.find(col_filter)
end_time = str(now_time())[0:19]
if coll.count_documents(col_filter) > 0:
start_time = ref_[coll.count_documents(
col_filter) - 1]["datetime"]
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"].index(type_),
str(code)[0:6],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = jqdatasdk.get_price(
security=code,
start_date=start_time,
end_date=end_time,
frequency=type_.split("min")[0]+"m",
)
__data = __transform_jq_to_qa(
df, code=code[:6], type_=type_)
if len(__data) > 1:
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
else:
start_time = "2015-01-01 09:30:00"
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"].index(type_),
str(code)[0:6],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
__data == __transform_jq_to_qa(
jqdatasdk.get_price(
security=code,
start_date=start_time,
end_date=end_time,
frequency=type_.split("min")[0]+"m",
),
code=code[:6],
type_=type_
)
if len(__data) > 1:
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
except Exception as e:
QA_util_log_info(e, ui_log=ui_log)
err.append(code)
QA_util_log_info(err, ui_log=ui_log)
# 聚宽之多允许三个线程连接
executor = ThreadPoolExecutor(max_workers=2)
res = {
executor.submit(__saving_work, code_list[i_], coll)
for i_ in range(len(code_list))
}
count = 0
for i_ in concurrent.futures.as_completed(res):
QA_util_log_info(
'The {} of Total {}'.format(count,
len(code_list)),
ui_log=ui_log
)
strProgress = "DOWNLOAD PROGRESS {} ".format(
str(float(count / len(code_list) * 100))[0:4] + "%")
intProgress = int(count / len(code_list) * 10000.0)
QA_util_log_info(
strProgress,
ui_log,
ui_progress=ui_progress,
ui_progress_int_value=intProgress
)
count = count + 1
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log) | [
"聚宽实现方式",
"save",
"current",
"day",
"s",
"stock_min",
"data"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/save_jq.py#L34-L207 | [
"def",
"QA_SU_save_stock_min",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"# 导入聚宽模块且进行登录",
"try",
":",
"import",
"jqdatasdk",
"# 请自行将 JQUSERNAME 和 JQUSERPASSWD 修改为自己的账号密码",
"jqdatasdk",
".",
"auth",
"(",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | execute | Execute a command on the command-line.
:param str,list command: The command to run
:param bool shell: Whether or not to use the shell. This is optional; if
``command`` is a basestring, shell will be set to True, otherwise it will
be false. You can override this behavior by setting this parameter
directly.
:param str working_dir: The directory in which to run the command.
:param bool echo: Whether or not to print the output from the command to
stdout.
:param int echo_indent: Any number of spaces to indent the echo for clarity
:returns: tuple: (return code, stdout)
Example
>>> from executor import execute
>>> return_code, text = execute("dir") | QUANTAXIS/QASetting/executor.py | def execute(command, shell=None, working_dir=".", echo=False, echo_indent=0):
"""Execute a command on the command-line.
:param str,list command: The command to run
:param bool shell: Whether or not to use the shell. This is optional; if
``command`` is a basestring, shell will be set to True, otherwise it will
be false. You can override this behavior by setting this parameter
directly.
:param str working_dir: The directory in which to run the command.
:param bool echo: Whether or not to print the output from the command to
stdout.
:param int echo_indent: Any number of spaces to indent the echo for clarity
:returns: tuple: (return code, stdout)
Example
>>> from executor import execute
>>> return_code, text = execute("dir")
"""
if shell is None:
shell = True if isinstance(command, str) else False
p = Popen(command, stdin=PIPE, stdout=PIPE,
stderr=STDOUT, shell=shell, cwd=working_dir)
if echo:
stdout = ""
while p.poll() is None:
# This blocks until it receives a newline.
line = p.stdout.readline()
print(" " * echo_indent, line, end="")
stdout += line
# Read any last bits
line = p.stdout.read()
print(" " * echo_indent, line, end="")
print()
stdout += line
else:
stdout, _ = p.communicate()
return (p.returncode, stdout) | def execute(command, shell=None, working_dir=".", echo=False, echo_indent=0):
"""Execute a command on the command-line.
:param str,list command: The command to run
:param bool shell: Whether or not to use the shell. This is optional; if
``command`` is a basestring, shell will be set to True, otherwise it will
be false. You can override this behavior by setting this parameter
directly.
:param str working_dir: The directory in which to run the command.
:param bool echo: Whether or not to print the output from the command to
stdout.
:param int echo_indent: Any number of spaces to indent the echo for clarity
:returns: tuple: (return code, stdout)
Example
>>> from executor import execute
>>> return_code, text = execute("dir")
"""
if shell is None:
shell = True if isinstance(command, str) else False
p = Popen(command, stdin=PIPE, stdout=PIPE,
stderr=STDOUT, shell=shell, cwd=working_dir)
if echo:
stdout = ""
while p.poll() is None:
# This blocks until it receives a newline.
line = p.stdout.readline()
print(" " * echo_indent, line, end="")
stdout += line
# Read any last bits
line = p.stdout.read()
print(" " * echo_indent, line, end="")
print()
stdout += line
else:
stdout, _ = p.communicate()
return (p.returncode, stdout) | [
"Execute",
"a",
"command",
"on",
"the",
"command",
"-",
"line",
".",
":",
"param",
"str",
"list",
"command",
":",
"The",
"command",
"to",
"run",
":",
"param",
"bool",
"shell",
":",
"Whether",
"or",
"not",
"to",
"use",
"the",
"shell",
".",
"This",
"is... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/executor.py#L33-L71 | [
"def",
"execute",
"(",
"command",
",",
"shell",
"=",
"None",
",",
"working_dir",
"=",
"\".\"",
",",
"echo",
"=",
"False",
",",
"echo_indent",
"=",
"0",
")",
":",
"if",
"shell",
"is",
"None",
":",
"shell",
"=",
"True",
"if",
"isinstance",
"(",
"comman... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_data_calc_marketvalue | 使用数据库数据计算复权 | QUANTAXIS/QAData/data_marketvalue.py | def QA_data_calc_marketvalue(data, xdxr):
'使用数据库数据计算复权'
mv = xdxr.query('category!=6').loc[:,
['shares_after',
'liquidity_after']].dropna()
res = pd.concat([data, mv], axis=1)
res = res.assign(
shares=res.shares_after.fillna(method='ffill'),
lshares=res.liquidity_after.fillna(method='ffill')
)
return res.assign(mv=res.close*res.shares*10000, liquidity_mv=res.close*res.lshares*10000).drop(['shares_after', 'liquidity_after'], axis=1)\
.loc[(slice(data.index.remove_unused_levels().levels[0][0],data.index.remove_unused_levels().levels[0][-1]),slice(None)),:] | def QA_data_calc_marketvalue(data, xdxr):
'使用数据库数据计算复权'
mv = xdxr.query('category!=6').loc[:,
['shares_after',
'liquidity_after']].dropna()
res = pd.concat([data, mv], axis=1)
res = res.assign(
shares=res.shares_after.fillna(method='ffill'),
lshares=res.liquidity_after.fillna(method='ffill')
)
return res.assign(mv=res.close*res.shares*10000, liquidity_mv=res.close*res.lshares*10000).drop(['shares_after', 'liquidity_after'], axis=1)\
.loc[(slice(data.index.remove_unused_levels().levels[0][0],data.index.remove_unused_levels().levels[0][-1]),slice(None)),:] | [
"使用数据库数据计算复权"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_marketvalue.py#L32-L44 | [
"def",
"QA_data_calc_marketvalue",
"(",
"data",
",",
"xdxr",
")",
":",
"mv",
"=",
"xdxr",
".",
"query",
"(",
"'category!=6'",
")",
".",
"loc",
"[",
":",
",",
"[",
"'shares_after'",
",",
"'liquidity_after'",
"]",
"]",
".",
"dropna",
"(",
")",
"res",
"="... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | MACD_JCSC | 1.DIF向上突破DEA,买入信号参考。
2.DIF向下跌破DEA,卖出信号参考。 | EXAMPLE/4_回测实盘交易/回测/股票回测/超级简化版回测/MACD_JCSC.py | def MACD_JCSC(dataframe, SHORT=12, LONG=26, M=9):
"""
1.DIF向上突破DEA,买入信号参考。
2.DIF向下跌破DEA,卖出信号参考。
"""
CLOSE = dataframe.close
DIFF = QA.EMA(CLOSE, SHORT) - QA.EMA(CLOSE, LONG)
DEA = QA.EMA(DIFF, M)
MACD = 2*(DIFF-DEA)
CROSS_JC = QA.CROSS(DIFF, DEA)
CROSS_SC = QA.CROSS(DEA, DIFF)
ZERO = 0
return pd.DataFrame({'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD, 'CROSS_JC': CROSS_JC, 'CROSS_SC': CROSS_SC, 'ZERO': ZERO}) | def MACD_JCSC(dataframe, SHORT=12, LONG=26, M=9):
"""
1.DIF向上突破DEA,买入信号参考。
2.DIF向下跌破DEA,卖出信号参考。
"""
CLOSE = dataframe.close
DIFF = QA.EMA(CLOSE, SHORT) - QA.EMA(CLOSE, LONG)
DEA = QA.EMA(DIFF, M)
MACD = 2*(DIFF-DEA)
CROSS_JC = QA.CROSS(DIFF, DEA)
CROSS_SC = QA.CROSS(DEA, DIFF)
ZERO = 0
return pd.DataFrame({'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD, 'CROSS_JC': CROSS_JC, 'CROSS_SC': CROSS_SC, 'ZERO': ZERO}) | [
"1",
".",
"DIF向上突破DEA,买入信号参考。",
"2",
".",
"DIF向下跌破DEA,卖出信号参考。"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/EXAMPLE/4_回测实盘交易/回测/股票回测/超级简化版回测/MACD_JCSC.py#L13-L26 | [
"def",
"MACD_JCSC",
"(",
"dataframe",
",",
"SHORT",
"=",
"12",
",",
"LONG",
"=",
"26",
",",
"M",
"=",
"9",
")",
":",
"CLOSE",
"=",
"dataframe",
".",
"close",
"DIFF",
"=",
"QA",
".",
"EMA",
"(",
"CLOSE",
",",
"SHORT",
")",
"-",
"QA",
".",
"EMA",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | Cache._create | Create the tables needed to store the information. | QUANTAXIS/QASetting/cache.py | def _create(self, cache_file):
"""Create the tables needed to store the information."""
conn = sqlite3.connect(cache_file)
cur = conn.cursor()
cur.execute("PRAGMA foreign_keys = ON")
cur.execute('''
CREATE TABLE jobs(
hash TEXT NOT NULL UNIQUE PRIMARY KEY, description TEXT NOT NULL,
last_run REAL, next_run REAL, last_run_result INTEGER)''')
cur.execute('''
CREATE TABLE history(
hash TEXT, description TEXT, time REAL, result INTEGER,
FOREIGN KEY(hash) REFERENCES jobs(hash))''')
conn.commit()
conn.close() | def _create(self, cache_file):
"""Create the tables needed to store the information."""
conn = sqlite3.connect(cache_file)
cur = conn.cursor()
cur.execute("PRAGMA foreign_keys = ON")
cur.execute('''
CREATE TABLE jobs(
hash TEXT NOT NULL UNIQUE PRIMARY KEY, description TEXT NOT NULL,
last_run REAL, next_run REAL, last_run_result INTEGER)''')
cur.execute('''
CREATE TABLE history(
hash TEXT, description TEXT, time REAL, result INTEGER,
FOREIGN KEY(hash) REFERENCES jobs(hash))''')
conn.commit()
conn.close() | [
"Create",
"the",
"tables",
"needed",
"to",
"store",
"the",
"information",
"."
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/cache.py#L68-L84 | [
"def",
"_create",
"(",
"self",
",",
"cache_file",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"cache_file",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"PRAGMA foreign_keys = ON\"",
")",
"cur",
".",
"execute... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | Cache.get | Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise | QUANTAXIS/QASetting/cache.py | def get(self, id):
"""Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise
"""
self.cur.execute("SELECT * FROM jobs WHERE hash=?", (id,))
item = self.cur.fetchone()
if item:
return dict(zip(
("id", "description", "last-run", "next-run", "last-run-result"),
item))
return None | def get(self, id):
"""Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise
"""
self.cur.execute("SELECT * FROM jobs WHERE hash=?", (id,))
item = self.cur.fetchone()
if item:
return dict(zip(
("id", "description", "last-run", "next-run", "last-run-result"),
item))
return None | [
"Retrieves",
"the",
"job",
"with",
"the",
"selected",
"ID",
".",
":",
"param",
"str",
"id",
":",
"The",
"ID",
"of",
"the",
"job",
":",
"returns",
":",
"The",
"dictionary",
"of",
"the",
"job",
"if",
"found",
"None",
"otherwise"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/cache.py#L93-L105 | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"\"SELECT * FROM jobs WHERE hash=?\"",
",",
"(",
"id",
",",
")",
")",
"item",
"=",
"self",
".",
"cur",
".",
"fetchone",
"(",
")",
"if",
"item",
":",
"return",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | Cache.update | Update last_run, next_run, and last_run_result for an existing job.
:param dict job: The job dictionary
:returns: True | QUANTAXIS/QASetting/cache.py | def update(self, job):
"""Update last_run, next_run, and last_run_result for an existing job.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute('''UPDATE jobs
SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''', (
job["last-run"], job["next-run"], job["last-run-result"], job["id"])) | def update(self, job):
"""Update last_run, next_run, and last_run_result for an existing job.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute('''UPDATE jobs
SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''', (
job["last-run"], job["next-run"], job["last-run-result"], job["id"])) | [
"Update",
"last_run",
"next_run",
"and",
"last_run_result",
"for",
"an",
"existing",
"job",
".",
":",
"param",
"dict",
"job",
":",
"The",
"job",
"dictionary",
":",
"returns",
":",
"True"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/cache.py#L107-L114 | [
"def",
"update",
"(",
"self",
",",
"job",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"'''UPDATE jobs\n SET last_run=?,next_run=?,last_run_result=? WHERE hash=?'''",
",",
"(",
"job",
"[",
"\"last-run\"",
"]",
",",
"job",
"[",
"\"next-run\"",
"]",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | Cache.add_job | Adds a new job into the cache.
:param dict job: The job dictionary
:returns: True | QUANTAXIS/QASetting/cache.py | def add_job(self, job):
"""Adds a new job into the cache.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute("INSERT INTO jobs VALUES(?,?,?,?,?)", (
job["id"], job["description"], job["last-run"], job["next-run"], job["last-run-result"]))
return True | def add_job(self, job):
"""Adds a new job into the cache.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute("INSERT INTO jobs VALUES(?,?,?,?,?)", (
job["id"], job["description"], job["last-run"], job["next-run"], job["last-run-result"]))
return True | [
"Adds",
"a",
"new",
"job",
"into",
"the",
"cache",
".",
":",
"param",
"dict",
"job",
":",
"The",
"job",
"dictionary",
":",
"returns",
":",
"True"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/cache.py#L116-L124 | [
"def",
"add_job",
"(",
"self",
",",
"job",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"\"INSERT INTO jobs VALUES(?,?,?,?,?)\"",
",",
"(",
"job",
"[",
"\"id\"",
"]",
",",
"job",
"[",
"\"description\"",
"]",
",",
"job",
"[",
"\"last-run\"",
"]",
",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | Cache.add_result | Adds a job run result to the history table.
:param dict job: The job dictionary
:returns: True | QUANTAXIS/QASetting/cache.py | def add_result(self, job):
"""Adds a job run result to the history table.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute(
"INSERT INTO history VALUES(?,?,?,?)",
(job["id"], job["description"], job["last-run"], job["last-run-result"]))
return True | def add_result(self, job):
"""Adds a job run result to the history table.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute(
"INSERT INTO history VALUES(?,?,?,?)",
(job["id"], job["description"], job["last-run"], job["last-run-result"]))
return True | [
"Adds",
"a",
"job",
"run",
"result",
"to",
"the",
"history",
"table",
".",
":",
"param",
"dict",
"job",
":",
"The",
"job",
"dictionary",
":",
"returns",
":",
"True"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASetting/cache.py#L126-L135 | [
"def",
"add_result",
"(",
"self",
",",
"job",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"\"INSERT INTO history VALUES(?,?,?,?)\"",
",",
"(",
"job",
"[",
"\"id\"",
"]",
",",
"job",
"[",
"\"description\"",
"]",
",",
"job",
"[",
"\"last-run\"",
"]",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_data_tick_resample_1min | tick 采样为 分钟数据
1. 仅使用将 tick 采样为 1 分钟数据
2. 仅测试过,与通达信 1 分钟数据达成一致
3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试
demo:
df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001',
start='2018-08-01 09:25:00',
end='2018-08-03 15:00:00')
df_min = QA_data_tick_resample_1min(df) | QUANTAXIS/QAData/data_resample.py | def QA_data_tick_resample_1min(tick, type_='1min', if_drop=True):
"""
tick 采样为 分钟数据
1. 仅使用将 tick 采样为 1 分钟数据
2. 仅测试过,与通达信 1 分钟数据达成一致
3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试
demo:
df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001',
start='2018-08-01 09:25:00',
end='2018-08-03 15:00:00')
df_min = QA_data_tick_resample_1min(df)
"""
tick = tick.assign(amount=tick.price * tick.vol)
resx = pd.DataFrame()
_dates = set(tick.date)
for date in sorted(list(_dates)):
_data = tick.loc[tick.date == date]
# morning min bar
_data1 = _data[time(9,
25):time(11,
30)].resample(
type_,
closed='left',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data1.columns = _data1.columns.droplevel(0)
# do fix on the first and last bar
# 某些股票某些日期没有集合竞价信息,譬如 002468 在 2017 年 6 月 5 日的数据
if len(_data.loc[time(9, 25):time(9, 25)]) > 0:
_data1.loc[time(9,
31):time(9,
31),
'open'] = _data1.loc[time(9,
26):time(9,
26),
'open'].values
_data1.loc[time(9,
31):time(9,
31),
'high'] = _data1.loc[time(9,
26):time(9,
31),
'high'].max()
_data1.loc[time(9,
31):time(9,
31),
'low'] = _data1.loc[time(9,
26):time(9,
31),
'low'].min()
_data1.loc[time(9,
31):time(9,
31),
'vol'] = _data1.loc[time(9,
26):time(9,
31),
'vol'].sum()
_data1.loc[time(9,
31):time(9,
31),
'amount'] = _data1.loc[time(9,
26):time(9,
31),
'amount'].sum()
# 通达信分笔数据有的有 11:30 数据,有的没有
if len(_data.loc[time(11, 30):time(11, 30)]) > 0:
_data1.loc[time(11,
30):time(11,
30),
'high'] = _data1.loc[time(11,
30):time(11,
31),
'high'].max()
_data1.loc[time(11,
30):time(11,
30),
'low'] = _data1.loc[time(11,
30):time(11,
31),
'low'].min()
_data1.loc[time(11,
30):time(11,
30),
'close'] = _data1.loc[time(11,
31):time(11,
31),
'close'].values
_data1.loc[time(11,
30):time(11,
30),
'vol'] = _data1.loc[time(11,
30):time(11,
31),
'vol'].sum()
_data1.loc[time(11,
30):time(11,
30),
'amount'] = _data1.loc[time(11,
30):time(11,
31),
'amount'].sum()
_data1 = _data1.loc[time(9, 31):time(11, 30)]
# afternoon min bar
_data2 = _data[time(13,
0):time(15,
0)].resample(
type_,
closed='left',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data2.columns = _data2.columns.droplevel(0)
# 沪市股票在 2018-08-20 起,尾盘 3 分钟集合竞价
if (pd.Timestamp(date) <
pd.Timestamp('2018-08-20')) and (tick.code.iloc[0][0] == '6'):
# 避免出现 tick 数据没有 1:00 的值
if len(_data.loc[time(13, 0):time(13, 0)]) > 0:
_data2.loc[time(15,
0):time(15,
0),
'high'] = _data2.loc[time(15,
0):time(15,
1),
'high'].max()
_data2.loc[time(15,
0):time(15,
0),
'low'] = _data2.loc[time(15,
0):time(15,
1),
'low'].min()
_data2.loc[time(15,
0):time(15,
0),
'close'] = _data2.loc[time(15,
1):time(15,
1),
'close'].values
else:
# 避免出现 tick 数据没有 15:00 的值
if len(_data.loc[time(13, 0):time(13, 0)]) > 0:
_data2.loc[time(15,
0):time(15,
0)] = _data2.loc[time(15,
1):time(15,
1)].values
_data2 = _data2.loc[time(13, 1):time(15, 0)]
resx = resx.append(_data1).append(_data2)
resx['vol'] = resx['vol'] * 100.0
resx['volume'] = resx['vol']
resx['type'] = '1min'
if if_drop:
resx = resx.dropna()
return resx.reset_index().drop_duplicates().set_index(['datetime', 'code']) | def QA_data_tick_resample_1min(tick, type_='1min', if_drop=True):
"""
tick 采样为 分钟数据
1. 仅使用将 tick 采样为 1 分钟数据
2. 仅测试过,与通达信 1 分钟数据达成一致
3. 经测试,可以匹配 QA.QA_fetch_get_stock_transaction 得到的数据,其他类型数据未测试
demo:
df = QA.QA_fetch_get_stock_transaction(package='tdx', code='000001',
start='2018-08-01 09:25:00',
end='2018-08-03 15:00:00')
df_min = QA_data_tick_resample_1min(df)
"""
tick = tick.assign(amount=tick.price * tick.vol)
resx = pd.DataFrame()
_dates = set(tick.date)
for date in sorted(list(_dates)):
_data = tick.loc[tick.date == date]
# morning min bar
_data1 = _data[time(9,
25):time(11,
30)].resample(
type_,
closed='left',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data1.columns = _data1.columns.droplevel(0)
# do fix on the first and last bar
# 某些股票某些日期没有集合竞价信息,譬如 002468 在 2017 年 6 月 5 日的数据
if len(_data.loc[time(9, 25):time(9, 25)]) > 0:
_data1.loc[time(9,
31):time(9,
31),
'open'] = _data1.loc[time(9,
26):time(9,
26),
'open'].values
_data1.loc[time(9,
31):time(9,
31),
'high'] = _data1.loc[time(9,
26):time(9,
31),
'high'].max()
_data1.loc[time(9,
31):time(9,
31),
'low'] = _data1.loc[time(9,
26):time(9,
31),
'low'].min()
_data1.loc[time(9,
31):time(9,
31),
'vol'] = _data1.loc[time(9,
26):time(9,
31),
'vol'].sum()
_data1.loc[time(9,
31):time(9,
31),
'amount'] = _data1.loc[time(9,
26):time(9,
31),
'amount'].sum()
# 通达信分笔数据有的有 11:30 数据,有的没有
if len(_data.loc[time(11, 30):time(11, 30)]) > 0:
_data1.loc[time(11,
30):time(11,
30),
'high'] = _data1.loc[time(11,
30):time(11,
31),
'high'].max()
_data1.loc[time(11,
30):time(11,
30),
'low'] = _data1.loc[time(11,
30):time(11,
31),
'low'].min()
_data1.loc[time(11,
30):time(11,
30),
'close'] = _data1.loc[time(11,
31):time(11,
31),
'close'].values
_data1.loc[time(11,
30):time(11,
30),
'vol'] = _data1.loc[time(11,
30):time(11,
31),
'vol'].sum()
_data1.loc[time(11,
30):time(11,
30),
'amount'] = _data1.loc[time(11,
30):time(11,
31),
'amount'].sum()
_data1 = _data1.loc[time(9, 31):time(11, 30)]
# afternoon min bar
_data2 = _data[time(13,
0):time(15,
0)].resample(
type_,
closed='left',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data2.columns = _data2.columns.droplevel(0)
# 沪市股票在 2018-08-20 起,尾盘 3 分钟集合竞价
if (pd.Timestamp(date) <
pd.Timestamp('2018-08-20')) and (tick.code.iloc[0][0] == '6'):
# 避免出现 tick 数据没有 1:00 的值
if len(_data.loc[time(13, 0):time(13, 0)]) > 0:
_data2.loc[time(15,
0):time(15,
0),
'high'] = _data2.loc[time(15,
0):time(15,
1),
'high'].max()
_data2.loc[time(15,
0):time(15,
0),
'low'] = _data2.loc[time(15,
0):time(15,
1),
'low'].min()
_data2.loc[time(15,
0):time(15,
0),
'close'] = _data2.loc[time(15,
1):time(15,
1),
'close'].values
else:
# 避免出现 tick 数据没有 15:00 的值
if len(_data.loc[time(13, 0):time(13, 0)]) > 0:
_data2.loc[time(15,
0):time(15,
0)] = _data2.loc[time(15,
1):time(15,
1)].values
_data2 = _data2.loc[time(13, 1):time(15, 0)]
resx = resx.append(_data1).append(_data2)
resx['vol'] = resx['vol'] * 100.0
resx['volume'] = resx['vol']
resx['type'] = '1min'
if if_drop:
resx = resx.dropna()
return resx.reset_index().drop_duplicates().set_index(['datetime', 'code']) | [
"tick",
"采样为",
"分钟数据",
"1",
".",
"仅使用将",
"tick",
"采样为",
"1",
"分钟数据",
"2",
".",
"仅测试过,与通达信",
"1",
"分钟数据达成一致",
"3",
".",
"经测试,可以匹配",
"QA",
".",
"QA_fetch_get_stock_transaction",
"得到的数据,其他类型数据未测试",
"demo",
":",
"df",
"=",
"QA",
".",
"QA_fetch_get_stock_transactio... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L30-L201 | [
"def",
"QA_data_tick_resample_1min",
"(",
"tick",
",",
"type_",
"=",
"'1min'",
",",
"if_drop",
"=",
"True",
")",
":",
"tick",
"=",
"tick",
".",
"assign",
"(",
"amount",
"=",
"tick",
".",
"price",
"*",
"tick",
".",
"vol",
")",
"resx",
"=",
"pd",
".",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_data_tick_resample | tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description] | QUANTAXIS/QAData/data_resample.py | def QA_data_tick_resample(tick, type_='1min'):
"""tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description]
"""
tick = tick.assign(amount=tick.price * tick.vol)
resx = pd.DataFrame()
_temp = set(tick.index.date)
for item in _temp:
_data = tick.loc[str(item)]
_data1 = _data[time(9,
31):time(11,
30)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data2 = _data[time(13,
1):time(15,
0)].resample(
type_,
closed='right',
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
resx = resx.append(_data1).append(_data2)
resx.columns = resx.columns.droplevel(0)
return resx.reset_index().drop_duplicates().set_index(['datetime', 'code']) | def QA_data_tick_resample(tick, type_='1min'):
"""tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description]
"""
tick = tick.assign(amount=tick.price * tick.vol)
resx = pd.DataFrame()
_temp = set(tick.index.date)
for item in _temp:
_data = tick.loc[str(item)]
_data1 = _data[time(9,
31):time(11,
30)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data2 = _data[time(13,
1):time(15,
0)].resample(
type_,
closed='right',
loffset=type_
).apply(
{
'price': 'ohlc',
'vol': 'sum',
'code': 'last',
'amount': 'sum'
}
)
resx = resx.append(_data1).append(_data2)
resx.columns = resx.columns.droplevel(0)
return resx.reset_index().drop_duplicates().set_index(['datetime', 'code']) | [
"tick采样成任意级别分钟线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L204-L252 | [
"def",
"QA_data_tick_resample",
"(",
"tick",
",",
"type_",
"=",
"'1min'",
")",
":",
"tick",
"=",
"tick",
".",
"assign",
"(",
"amount",
"=",
"tick",
".",
"price",
"*",
"tick",
".",
"vol",
")",
"resx",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"_temp",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_data_ctptick_resample | tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description] | QUANTAXIS/QAData/data_resample.py | def QA_data_ctptick_resample(tick, type_='1min'):
"""tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description]
"""
resx = pd.DataFrame()
_temp = set(tick.TradingDay)
for item in _temp:
_data = tick.query('TradingDay=="{}"'.format(item))
try:
_data.loc[time(20, 0):time(21, 0), 'volume'] = 0
except:
pass
_data.volume = _data.volume.diff()
_data = _data.assign(amount=_data.LastPrice * _data.volume)
_data0 = _data[time(0,
0):time(2,
30)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data1 = _data[time(9,
0):time(11,
30)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data2 = _data[time(13,
1):time(15,
0)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data3 = _data[time(21,
0):time(23,
59)].resample(
type_,
closed='left',
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
resx = resx.append(_data0).append(_data1).append(_data2).append(_data3)
resx.columns = resx.columns.droplevel(0)
return resx.reset_index().drop_duplicates().set_index(['datetime',
'code']).sort_index() | def QA_data_ctptick_resample(tick, type_='1min'):
"""tick采样成任意级别分钟线
Arguments:
tick {[type]} -- transaction
Returns:
[type] -- [description]
"""
resx = pd.DataFrame()
_temp = set(tick.TradingDay)
for item in _temp:
_data = tick.query('TradingDay=="{}"'.format(item))
try:
_data.loc[time(20, 0):time(21, 0), 'volume'] = 0
except:
pass
_data.volume = _data.volume.diff()
_data = _data.assign(amount=_data.LastPrice * _data.volume)
_data0 = _data[time(0,
0):time(2,
30)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data1 = _data[time(9,
0):time(11,
30)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data2 = _data[time(13,
1):time(15,
0)].resample(
type_,
closed='right',
base=30,
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
_data3 = _data[time(21,
0):time(23,
59)].resample(
type_,
closed='left',
loffset=type_
).apply(
{
'LastPrice': 'ohlc',
'volume': 'sum',
'code': 'last',
'amount': 'sum'
}
)
resx = resx.append(_data0).append(_data1).append(_data2).append(_data3)
resx.columns = resx.columns.droplevel(0)
return resx.reset_index().drop_duplicates().set_index(['datetime',
'code']).sort_index() | [
"tick采样成任意级别分钟线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L255-L344 | [
"def",
"QA_data_ctptick_resample",
"(",
"tick",
",",
"type_",
"=",
"'1min'",
")",
":",
"resx",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"_temp",
"=",
"set",
"(",
"tick",
".",
"TradingDay",
")",
"for",
"item",
"in",
"_temp",
":",
"_data",
"=",
"tick",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_data_min_resample | 分钟线采样成大周期
分钟线采样成子级别的分钟线
time+ OHLC==> resample
Arguments:
min {[type]} -- [description]
raw_type {[type]} -- [description]
new_type {[type]} -- [description] | QUANTAXIS/QAData/data_resample.py | def QA_data_min_resample(min_data, type_='5min'):
"""分钟线采样成大周期
分钟线采样成子级别的分钟线
time+ OHLC==> resample
Arguments:
min {[type]} -- [description]
raw_type {[type]} -- [description]
new_type {[type]} -- [description]
"""
try:
min_data = min_data.reset_index().set_index('datetime', drop=False)
except:
min_data = min_data.set_index('datetime', drop=False)
CONVERSION = {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'vol': 'sum',
'amount': 'sum'
} if 'vol' in min_data.columns else {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum',
'amount': 'sum'
}
resx = pd.DataFrame()
for item in set(min_data.index.date):
min_data_p = min_data.loc[str(item)]
n = min_data_p['{} 21:00:00'.format(item):].resample(
type_,
base=30,
closed='right',
loffset=type_
).apply(CONVERSION)
d = min_data_p[:'{} 11:30:00'.format(item)].resample(
type_,
base=30,
closed='right',
loffset=type_
).apply(CONVERSION)
f = min_data_p['{} 13:00:00'.format(item):].resample(
type_,
closed='right',
loffset=type_
).apply(CONVERSION)
resx = resx.append(d).append(f)
return resx.dropna().reset_index().set_index(['datetime', 'code']) | def QA_data_min_resample(min_data, type_='5min'):
"""分钟线采样成大周期
分钟线采样成子级别的分钟线
time+ OHLC==> resample
Arguments:
min {[type]} -- [description]
raw_type {[type]} -- [description]
new_type {[type]} -- [description]
"""
try:
min_data = min_data.reset_index().set_index('datetime', drop=False)
except:
min_data = min_data.set_index('datetime', drop=False)
CONVERSION = {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'vol': 'sum',
'amount': 'sum'
} if 'vol' in min_data.columns else {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum',
'amount': 'sum'
}
resx = pd.DataFrame()
for item in set(min_data.index.date):
min_data_p = min_data.loc[str(item)]
n = min_data_p['{} 21:00:00'.format(item):].resample(
type_,
base=30,
closed='right',
loffset=type_
).apply(CONVERSION)
d = min_data_p[:'{} 11:30:00'.format(item)].resample(
type_,
base=30,
closed='right',
loffset=type_
).apply(CONVERSION)
f = min_data_p['{} 13:00:00'.format(item):].resample(
type_,
closed='right',
loffset=type_
).apply(CONVERSION)
resx = resx.append(d).append(f)
return resx.dropna().reset_index().set_index(['datetime', 'code']) | [
"分钟线采样成大周期"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L347-L408 | [
"def",
"QA_data_min_resample",
"(",
"min_data",
",",
"type_",
"=",
"'5min'",
")",
":",
"try",
":",
"min_data",
"=",
"min_data",
".",
"reset_index",
"(",
")",
".",
"set_index",
"(",
"'datetime'",
",",
"drop",
"=",
"False",
")",
"except",
":",
"min_data",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_data_futuremin_resample | 期货分钟线采样成大周期
分钟线采样成子级别的分钟线
future:
vol ==> trade
amount X | QUANTAXIS/QAData/data_resample.py | def QA_data_futuremin_resample(min_data, type_='5min'):
"""期货分钟线采样成大周期
分钟线采样成子级别的分钟线
future:
vol ==> trade
amount X
"""
min_data.tradeime = pd.to_datetime(min_data.tradetime)
CONVERSION = {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'trade': 'sum',
'tradetime': 'last',
'date': 'last'
}
resx = min_data.resample(
type_,
closed='right',
loffset=type_
).apply(CONVERSION)
return resx.dropna().reset_index().set_index(['datetime', 'code']) | def QA_data_futuremin_resample(min_data, type_='5min'):
"""期货分钟线采样成大周期
分钟线采样成子级别的分钟线
future:
vol ==> trade
amount X
"""
min_data.tradeime = pd.to_datetime(min_data.tradetime)
CONVERSION = {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'trade': 'sum',
'tradetime': 'last',
'date': 'last'
}
resx = min_data.resample(
type_,
closed='right',
loffset=type_
).apply(CONVERSION)
return resx.dropna().reset_index().set_index(['datetime', 'code']) | [
"期货分钟线采样成大周期"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L411-L440 | [
"def",
"QA_data_futuremin_resample",
"(",
"min_data",
",",
"type_",
"=",
"'5min'",
")",
":",
"min_data",
".",
"tradeime",
"=",
"pd",
".",
"to_datetime",
"(",
"min_data",
".",
"tradetime",
")",
"CONVERSION",
"=",
"{",
"'code'",
":",
"'first'",
",",
"'open'",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_data_day_resample | 日线降采样
Arguments:
day_data {[type]} -- [description]
Keyword Arguments:
type_ {str} -- [description] (default: {'w'})
Returns:
[type] -- [description] | QUANTAXIS/QAData/data_resample.py | def QA_data_day_resample(day_data, type_='w'):
"""日线降采样
Arguments:
day_data {[type]} -- [description]
Keyword Arguments:
type_ {str} -- [description] (default: {'w'})
Returns:
[type] -- [description]
"""
# return day_data_p.assign(open=day_data.open.resample(type_).first(),high=day_data.high.resample(type_).max(),low=day_data.low.resample(type_).min(),\
# vol=day_data.vol.resample(type_).sum() if 'vol' in day_data.columns else day_data.volume.resample(type_).sum(),\
# amount=day_data.amount.resample(type_).sum()).dropna().set_index('date')
try:
day_data = day_data.reset_index().set_index('date', drop=False)
except:
day_data = day_data.set_index('date', drop=False)
CONVERSION = {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'vol': 'sum',
'amount': 'sum'
} if 'vol' in day_data.columns else {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum',
'amount': 'sum'
}
return day_data.resample(
type_,
closed='right'
).apply(CONVERSION).dropna().reset_index().set_index(['date',
'code']) | def QA_data_day_resample(day_data, type_='w'):
"""日线降采样
Arguments:
day_data {[type]} -- [description]
Keyword Arguments:
type_ {str} -- [description] (default: {'w'})
Returns:
[type] -- [description]
"""
# return day_data_p.assign(open=day_data.open.resample(type_).first(),high=day_data.high.resample(type_).max(),low=day_data.low.resample(type_).min(),\
# vol=day_data.vol.resample(type_).sum() if 'vol' in day_data.columns else day_data.volume.resample(type_).sum(),\
# amount=day_data.amount.resample(type_).sum()).dropna().set_index('date')
try:
day_data = day_data.reset_index().set_index('date', drop=False)
except:
day_data = day_data.set_index('date', drop=False)
CONVERSION = {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'vol': 'sum',
'amount': 'sum'
} if 'vol' in day_data.columns else {
'code': 'first',
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum',
'amount': 'sum'
}
return day_data.resample(
type_,
closed='right'
).apply(CONVERSION).dropna().reset_index().set_index(['date',
'code']) | [
"日线降采样"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/data_resample.py#L443-L485 | [
"def",
"QA_data_day_resample",
"(",
"day_data",
",",
"type_",
"=",
"'w'",
")",
":",
"# return day_data_p.assign(open=day_data.open.resample(type_).first(),high=day_data.high.resample(type_).max(),low=day_data.low.resample(type_).min(),\\",
"# vol=day_data.vol.resample(type_).sum() ... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_info | save stock info
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_stock_info(engine, client=DATABASE):
"""save stock info
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_info(client=client) | def QA_SU_save_stock_info(engine, client=DATABASE):
"""save stock info
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_info(client=client) | [
"save",
"stock",
"info"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L38-L49 | [
"def",
"QA_SU_save_stock_info",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_stock_info",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_list | save stock_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_stock_list(engine, client=DATABASE):
"""save stock_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_list(client=client) | def QA_SU_save_stock_list(engine, client=DATABASE):
"""save stock_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_list(client=client) | [
"save",
"stock_list"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L67-L78 | [
"def",
"QA_SU_save_stock_list",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_stock_list",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_index_list | save index_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_index_list(engine, client=DATABASE):
"""save index_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_index_list(client=client) | def QA_SU_save_index_list(engine, client=DATABASE):
"""save index_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_index_list(client=client) | [
"save",
"index_list"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L81-L92 | [
"def",
"QA_SU_save_index_list",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_index_list",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_etf_list | save etf_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_etf_list(engine, client=DATABASE):
"""save etf_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_list(client=client) | def QA_SU_save_etf_list(engine, client=DATABASE):
"""save etf_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_list(client=client) | [
"save",
"etf_list"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L95-L106 | [
"def",
"QA_SU_save_etf_list",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_etf_list",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_future_list | save future_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_future_list(engine, client=DATABASE):
"""save future_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_list(client=client) | def QA_SU_save_future_list(engine, client=DATABASE):
"""save future_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_list(client=client) | [
"save",
"future_list"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L109-L120 | [
"def",
"QA_SU_save_future_list",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_future_list",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_future_day | save future_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_future_day(engine, client=DATABASE):
"""save future_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_day(client=client) | def QA_SU_save_future_day(engine, client=DATABASE):
"""save future_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_day(client=client) | [
"save",
"future_day"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L123-L134 | [
"def",
"QA_SU_save_future_day",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_future_day",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_future_day_all | save future_day_all
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_future_day_all(engine, client=DATABASE):
"""save future_day_all
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_day_all(client=client) | def QA_SU_save_future_day_all(engine, client=DATABASE):
"""save future_day_all
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_day_all(client=client) | [
"save",
"future_day_all"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L137-L148 | [
"def",
"QA_SU_save_future_day_all",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_future_day_all",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_future_min | save future_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_future_min(engine, client=DATABASE):
"""save future_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_min(client=client) | def QA_SU_save_future_min(engine, client=DATABASE):
"""save future_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_min(client=client) | [
"save",
"future_min",
"Arguments",
":",
"engine",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L151-L161 | [
"def",
"QA_SU_save_future_min",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_future_min",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_future_min_all | [summary]
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_future_min_all(engine, client=DATABASE):
"""[summary]
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_min_all(client=client) | def QA_SU_save_future_min_all(engine, client=DATABASE):
"""[summary]
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_min_all(client=client) | [
"[",
"summary",
"]"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L164-L175 | [
"def",
"QA_SU_save_future_min_all",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_future_min_all",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_day | save stock_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_stock_day(engine, client=DATABASE, paralleled=False):
"""save stock_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine, paralleled=paralleled)
engine.QA_SU_save_stock_day(client=client) | def QA_SU_save_stock_day(engine, client=DATABASE, paralleled=False):
"""save stock_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine, paralleled=paralleled)
engine.QA_SU_save_stock_day(client=client) | [
"save",
"stock_day"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L178-L189 | [
"def",
"QA_SU_save_stock_day",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
",",
"paralleled",
"=",
"False",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
",",
"paralleled",
"=",
"paralleled",
")",
"engine",
".",
"QA_SU_save_stock_day",
"(",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_option_commodity_min | :param engine:
:param client:
:return: | QUANTAXIS/QASU/main.py | def QA_SU_save_option_commodity_min(engine, client=DATABASE):
'''
:param engine:
:param client:
:return:
'''
engine = select_save_engine(engine)
engine.QA_SU_save_option_commodity_min(client=client) | def QA_SU_save_option_commodity_min(engine, client=DATABASE):
'''
:param engine:
:param client:
:return:
'''
engine = select_save_engine(engine)
engine.QA_SU_save_option_commodity_min(client=client) | [
":",
"param",
"engine",
":",
":",
"param",
"client",
":",
":",
"return",
":"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L225-L232 | [
"def",
"QA_SU_save_option_commodity_min",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_option_commodity_min",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_option_commodity_day | :param engine:
:param client:
:return: | QUANTAXIS/QASU/main.py | def QA_SU_save_option_commodity_day(engine, client=DATABASE):
'''
:param engine:
:param client:
:return:
'''
engine = select_save_engine(engine)
engine.QA_SU_save_option_commodity_day(client=client) | def QA_SU_save_option_commodity_day(engine, client=DATABASE):
'''
:param engine:
:param client:
:return:
'''
engine = select_save_engine(engine)
engine.QA_SU_save_option_commodity_day(client=client) | [
":",
"param",
"engine",
":",
":",
"param",
"client",
":",
":",
"return",
":"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L235-L242 | [
"def",
"QA_SU_save_option_commodity_day",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_option_commodity_day",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_min | save stock_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_stock_min(engine, client=DATABASE):
"""save stock_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_min(client=client) | def QA_SU_save_stock_min(engine, client=DATABASE):
"""save stock_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_min(client=client) | [
"save",
"stock_min"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L245-L256 | [
"def",
"QA_SU_save_stock_min",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_stock_min",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_index_day | save index_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_index_day(engine, client=DATABASE):
"""save index_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_index_day(client=client) | def QA_SU_save_index_day(engine, client=DATABASE):
"""save index_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_index_day(client=client) | [
"save",
"index_day"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L259-L270 | [
"def",
"QA_SU_save_index_day",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_index_day",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_index_min | save index_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_index_min(engine, client=DATABASE):
"""save index_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_index_min(client=client) | def QA_SU_save_index_min(engine, client=DATABASE):
"""save index_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_index_min(client=client) | [
"save",
"index_min"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L273-L284 | [
"def",
"QA_SU_save_index_min",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_index_min",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_etf_day | save etf_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_etf_day(engine, client=DATABASE):
"""save etf_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_day(client=client) | def QA_SU_save_etf_day(engine, client=DATABASE):
"""save etf_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_day(client=client) | [
"save",
"etf_day"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L287-L298 | [
"def",
"QA_SU_save_etf_day",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_etf_day",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_etf_min | save etf_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_etf_min(engine, client=DATABASE):
"""save etf_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_min(client=client) | def QA_SU_save_etf_min(engine, client=DATABASE):
"""save etf_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_min(client=client) | [
"save",
"etf_min"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L301-L312 | [
"def",
"QA_SU_save_etf_min",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_etf_min",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_xdxr | save stock_xdxr
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_stock_xdxr(engine, client=DATABASE):
"""save stock_xdxr
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_xdxr(client=client) | def QA_SU_save_stock_xdxr(engine, client=DATABASE):
"""save stock_xdxr
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_xdxr(client=client) | [
"save",
"stock_xdxr"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L315-L326 | [
"def",
"QA_SU_save_stock_xdxr",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_stock_xdxr",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_SU_save_stock_block | save stock_block
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) | QUANTAXIS/QASU/main.py | def QA_SU_save_stock_block(engine, client=DATABASE):
"""save stock_block
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_block(client=client) | def QA_SU_save_stock_block(engine, client=DATABASE):
"""save stock_block
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_block(client=client) | [
"save",
"stock_block"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L329-L340 | [
"def",
"QA_SU_save_stock_block",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_stock_block",
"(",
"client",
"=",
"client",
")"
] | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | select_save_engine | select save_engine , tushare ts Tushare 使用 Tushare 免费数据接口, tdx 使用通达信数据接口
:param engine: 字符串Str
:param paralleled: 是否并行处理;默认为False
:return: sts means save_tushare_py or stdx means save_tdx_py | QUANTAXIS/QASU/main.py | def select_save_engine(engine, paralleled=False):
'''
select save_engine , tushare ts Tushare 使用 Tushare 免费数据接口, tdx 使用通达信数据接口
:param engine: 字符串Str
:param paralleled: 是否并行处理;默认为False
:return: sts means save_tushare_py or stdx means save_tdx_py
'''
if engine in ['tushare', 'ts', 'Tushare']:
return sts
elif engine in ['tdx']:
if paralleled:
return stdx_parallelism
else:
return stdx
elif engine in ['gm', 'goldenminer']:
return sgm
elif engine in ['jq', 'joinquant']:
return sjq
else:
print('QA Error QASU.main.py call select_save_engine with parameter %s is None of thshare, ts, Thshare, or tdx', engine) | def select_save_engine(engine, paralleled=False):
'''
select save_engine , tushare ts Tushare 使用 Tushare 免费数据接口, tdx 使用通达信数据接口
:param engine: 字符串Str
:param paralleled: 是否并行处理;默认为False
:return: sts means save_tushare_py or stdx means save_tdx_py
'''
if engine in ['tushare', 'ts', 'Tushare']:
return sts
elif engine in ['tdx']:
if paralleled:
return stdx_parallelism
else:
return stdx
elif engine in ['gm', 'goldenminer']:
return sgm
elif engine in ['jq', 'joinquant']:
return sjq
else:
print('QA Error QASU.main.py call select_save_engine with parameter %s is None of thshare, ts, Thshare, or tdx', engine) | [
"select",
"save_engine",
"tushare",
"ts",
"Tushare",
"使用",
"Tushare",
"免费数据接口,",
"tdx",
"使用通达信数据接口",
":",
"param",
"engine",
":",
"字符串Str",
":",
"param",
"paralleled",
":",
"是否并行处理;默认为False",
":",
"return",
":",
"sts",
"means",
"save_tushare_py",
"or",
"stdx",
... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QASU/main.py#L343-L362 | [
"def",
"select_save_engine",
"(",
"engine",
",",
"paralleled",
"=",
"False",
")",
":",
"if",
"engine",
"in",
"[",
"'tushare'",
",",
"'ts'",
",",
"'Tushare'",
"]",
":",
"return",
"sts",
"elif",
"engine",
"in",
"[",
"'tdx'",
"]",
":",
"if",
"paralleled",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_day | 获取股票日线'
Returns:
[type] -- [description]
感谢@几何大佬的提示
https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-the-specified-fields-and-the-id-field-only | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_day(code, start, end, format='numpy', frequence='day', collections=DATABASE.stock_day):
"""'获取股票日线'
Returns:
[type] -- [description]
感谢@几何大佬的提示
https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-the-specified-fields-and-the-id-field-only
"""
start = str(start)[0:10]
end = str(end)[0:10]
#code= [code] if isinstance(code,str) else code
# code checking
code = QA_util_code_tolist(code)
if QA_util_date_valid(end):
cursor = collections.find({
'code': {'$in': code}, "date_stamp": {
"$lte": QA_util_date_stamp(end),
"$gte": QA_util_date_stamp(start)}}, {"_id": 0}, batch_size=10000)
#res=[QA_util_dict_remove_key(data, '_id') for data in cursor]
res = pd.DataFrame([item for item in cursor])
try:
res = res.assign(volume=res.vol, date=pd.to_datetime(
res.date)).drop_duplicates((['date', 'code'])).query('volume>1').set_index('date', drop=False)
res = res.ix[:, ['code', 'open', 'high', 'low',
'close', 'volume', 'amount', 'date']]
except:
res = None
if format in ['P', 'p', 'pandas', 'pd']:
return res
elif format in ['json', 'dict']:
return QA_util_to_json_from_pandas(res)
# 多种数据格式
elif format in ['n', 'N', 'numpy']:
return numpy.asarray(res)
elif format in ['list', 'l', 'L']:
return numpy.asarray(res).tolist()
else:
print("QA Error QA_fetch_stock_day format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return None
else:
QA_util_log_info(
'QA Error QA_fetch_stock_day data parameter start=%s end=%s is not right' % (start, end)) | def QA_fetch_stock_day(code, start, end, format='numpy', frequence='day', collections=DATABASE.stock_day):
"""'获取股票日线'
Returns:
[type] -- [description]
感谢@几何大佬的提示
https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-the-specified-fields-and-the-id-field-only
"""
start = str(start)[0:10]
end = str(end)[0:10]
#code= [code] if isinstance(code,str) else code
# code checking
code = QA_util_code_tolist(code)
if QA_util_date_valid(end):
cursor = collections.find({
'code': {'$in': code}, "date_stamp": {
"$lte": QA_util_date_stamp(end),
"$gte": QA_util_date_stamp(start)}}, {"_id": 0}, batch_size=10000)
#res=[QA_util_dict_remove_key(data, '_id') for data in cursor]
res = pd.DataFrame([item for item in cursor])
try:
res = res.assign(volume=res.vol, date=pd.to_datetime(
res.date)).drop_duplicates((['date', 'code'])).query('volume>1').set_index('date', drop=False)
res = res.ix[:, ['code', 'open', 'high', 'low',
'close', 'volume', 'amount', 'date']]
except:
res = None
if format in ['P', 'p', 'pandas', 'pd']:
return res
elif format in ['json', 'dict']:
return QA_util_to_json_from_pandas(res)
# 多种数据格式
elif format in ['n', 'N', 'numpy']:
return numpy.asarray(res)
elif format in ['list', 'l', 'L']:
return numpy.asarray(res).tolist()
else:
print("QA Error QA_fetch_stock_day format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return None
else:
QA_util_log_info(
'QA Error QA_fetch_stock_day data parameter start=%s end=%s is not right' % (start, end)) | [
"获取股票日线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L48-L96 | [
"def",
"QA_fetch_stock_day",
"(",
"code",
",",
"start",
",",
"end",
",",
"format",
"=",
"'numpy'",
",",
"frequence",
"=",
"'day'",
",",
"collections",
"=",
"DATABASE",
".",
"stock_day",
")",
":",
"start",
"=",
"str",
"(",
"start",
")",
"[",
"0",
":",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_min | 获取股票分钟线 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_min(code, start, end, format='numpy', frequence='1min', collections=DATABASE.stock_min):
'获取股票分钟线'
if frequence in ['1min', '1m']:
frequence = '1min'
elif frequence in ['5min', '5m']:
frequence = '5min'
elif frequence in ['15min', '15m']:
frequence = '15min'
elif frequence in ['30min', '30m']:
frequence = '30min'
elif frequence in ['60min', '60m']:
frequence = '60min'
else:
print("QA Error QA_fetch_stock_min parameter frequence=%s is none of 1min 1m 5min 5m 15min 15m 30min 30m 60min 60m" % frequence)
__data = []
# code checking
code = QA_util_code_tolist(code)
cursor = collections.find({
'code': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, {"_id": 0}, batch_size=10000)
res = pd.DataFrame([item for item in cursor])
try:
res = res.assign(volume=res.vol, datetime=pd.to_datetime(
res.datetime)).query('volume>1').drop_duplicates(['datetime', 'code']).set_index('datetime', drop=False)
# return res
except:
res = None
if format in ['P', 'p', 'pandas', 'pd']:
return res
elif format in ['json', 'dict']:
return QA_util_to_json_from_pandas(res)
# 多种数据格式
elif format in ['n', 'N', 'numpy']:
return numpy.asarray(res)
elif format in ['list', 'l', 'L']:
return numpy.asarray(res).tolist()
else:
print("QA Error QA_fetch_stock_min format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return None | def QA_fetch_stock_min(code, start, end, format='numpy', frequence='1min', collections=DATABASE.stock_min):
'获取股票分钟线'
if frequence in ['1min', '1m']:
frequence = '1min'
elif frequence in ['5min', '5m']:
frequence = '5min'
elif frequence in ['15min', '15m']:
frequence = '15min'
elif frequence in ['30min', '30m']:
frequence = '30min'
elif frequence in ['60min', '60m']:
frequence = '60min'
else:
print("QA Error QA_fetch_stock_min parameter frequence=%s is none of 1min 1m 5min 5m 15min 15m 30min 30m 60min 60m" % frequence)
__data = []
# code checking
code = QA_util_code_tolist(code)
cursor = collections.find({
'code': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, {"_id": 0}, batch_size=10000)
res = pd.DataFrame([item for item in cursor])
try:
res = res.assign(volume=res.vol, datetime=pd.to_datetime(
res.datetime)).query('volume>1').drop_duplicates(['datetime', 'code']).set_index('datetime', drop=False)
# return res
except:
res = None
if format in ['P', 'p', 'pandas', 'pd']:
return res
elif format in ['json', 'dict']:
return QA_util_to_json_from_pandas(res)
# 多种数据格式
elif format in ['n', 'N', 'numpy']:
return numpy.asarray(res)
elif format in ['list', 'l', 'L']:
return numpy.asarray(res).tolist()
else:
print("QA Error QA_fetch_stock_min format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return None | [
"获取股票分钟线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L99-L143 | [
"def",
"QA_fetch_stock_min",
"(",
"code",
",",
"start",
",",
"end",
",",
"format",
"=",
"'numpy'",
",",
"frequence",
"=",
"'1min'",
",",
"collections",
"=",
"DATABASE",
".",
"stock_min",
")",
":",
"if",
"frequence",
"in",
"[",
"'1min'",
",",
"'1m'",
"]",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_list | 获取股票列表 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_list(collections=DATABASE.stock_list):
'获取股票列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | def QA_fetch_stock_list(collections=DATABASE.stock_list):
'获取股票列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | [
"获取股票列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L151-L154 | [
"def",
"QA_fetch_stock_list",
"(",
"collections",
"=",
"DATABASE",
".",
"stock_list",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"item",
"in",
"collections",
".",
"find",
"(",
")",
"]",
")",
".",
"drop",
"(",
"'_id'",
",",
"ax... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_etf_list | 获取ETF列表 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_etf_list(collections=DATABASE.etf_list):
'获取ETF列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | def QA_fetch_etf_list(collections=DATABASE.etf_list):
'获取ETF列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | [
"获取ETF列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L157-L160 | [
"def",
"QA_fetch_etf_list",
"(",
"collections",
"=",
"DATABASE",
".",
"etf_list",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"item",
"in",
"collections",
".",
"find",
"(",
")",
"]",
")",
".",
"drop",
"(",
"'_id'",
",",
"axis",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_index_list | 获取指数列表 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_index_list(collections=DATABASE.index_list):
'获取指数列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | def QA_fetch_index_list(collections=DATABASE.index_list):
'获取指数列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | [
"获取指数列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L163-L165 | [
"def",
"QA_fetch_index_list",
"(",
"collections",
"=",
"DATABASE",
".",
"index_list",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"item",
"in",
"collections",
".",
"find",
"(",
")",
"]",
")",
".",
"drop",
"(",
"'_id'",
",",
"ax... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_terminated | 获取股票基本信息 , 已经退市的股票列表 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_terminated(collections=DATABASE.stock_terminated):
'获取股票基本信息 , 已经退市的股票列表'
# 🛠todo 转变成 dataframe 类型数据
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | def QA_fetch_stock_terminated(collections=DATABASE.stock_terminated):
'获取股票基本信息 , 已经退市的股票列表'
# 🛠todo 转变成 dataframe 类型数据
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | [
"获取股票基本信息",
"已经退市的股票列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L168-L171 | [
"def",
"QA_fetch_stock_terminated",
"(",
"collections",
"=",
"DATABASE",
".",
"stock_terminated",
")",
":",
"# 🛠todo 转变成 dataframe 类型数据",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"item",
"in",
"collections",
".",
"find",
"(",
")",
"]",
")",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_basic_info_tushare | purpose:
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,
:param collections: stock_info_tushare 集合
:return: | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_basic_info_tushare(collections=DATABASE.stock_info_tushare):
'''
purpose:
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,
:param collections: stock_info_tushare 集合
:return:
'''
'获取股票基本信息'
items = [item for item in collections.find()]
# 🛠todo 转变成 dataframe 类型数据
return items | def QA_fetch_stock_basic_info_tushare(collections=DATABASE.stock_info_tushare):
'''
purpose:
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,
:param collections: stock_info_tushare 集合
:return:
'''
'获取股票基本信息'
items = [item for item in collections.find()]
# 🛠todo 转变成 dataframe 类型数据
return items | [
"purpose",
":",
"tushare",
"股票列表数据库"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L174-L211 | [
"def",
"QA_fetch_stock_basic_info_tushare",
"(",
"collections",
"=",
"DATABASE",
".",
"stock_info_tushare",
")",
":",
"'获取股票基本信息'",
"items",
"=",
"[",
"item",
"for",
"item",
"in",
"collections",
".",
"find",
"(",
")",
"]",
"# 🛠todo 转变成 dataframe 类型数据",
"return",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_full | 获取全市场的某一日的数据 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_full(date, format='numpy', collections=DATABASE.stock_day):
'获取全市场的某一日的数据'
Date = str(date)[0:10]
if QA_util_date_valid(Date) is True:
__data = []
for item in collections.find({
"date_stamp": QA_util_date_stamp(Date)}, batch_size=10000):
__data.append([str(item['code']), float(item['open']), float(item['high']), float(
item['low']), float(item['close']), float(item['vol']), item['date']])
# 多种数据格式
if format in ['n', 'N', 'numpy']:
__data = numpy.asarray(__data)
elif format in ['list', 'l', 'L']:
__data = __data
elif format in ['P', 'p', 'pandas', 'pd']:
__data = DataFrame(__data, columns=[
'code', 'open', 'high', 'low', 'close', 'volume', 'date'])
__data['date'] = pd.to_datetime(__data['date'])
__data = __data.set_index('date', drop=False)
else:
print("QA Error QA_fetch_stock_full format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return __data
else:
QA_util_log_info(
'QA Error QA_fetch_stock_full data parameter date=%s not right' % date) | def QA_fetch_stock_full(date, format='numpy', collections=DATABASE.stock_day):
'获取全市场的某一日的数据'
Date = str(date)[0:10]
if QA_util_date_valid(Date) is True:
__data = []
for item in collections.find({
"date_stamp": QA_util_date_stamp(Date)}, batch_size=10000):
__data.append([str(item['code']), float(item['open']), float(item['high']), float(
item['low']), float(item['close']), float(item['vol']), item['date']])
# 多种数据格式
if format in ['n', 'N', 'numpy']:
__data = numpy.asarray(__data)
elif format in ['list', 'l', 'L']:
__data = __data
elif format in ['P', 'p', 'pandas', 'pd']:
__data = DataFrame(__data, columns=[
'code', 'open', 'high', 'low', 'close', 'volume', 'date'])
__data['date'] = pd.to_datetime(__data['date'])
__data = __data.set_index('date', drop=False)
else:
print("QA Error QA_fetch_stock_full format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return __data
else:
QA_util_log_info(
'QA Error QA_fetch_stock_full data parameter date=%s not right' % date) | [
"获取全市场的某一日的数据"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L226-L252 | [
"def",
"QA_fetch_stock_full",
"(",
"date",
",",
"format",
"=",
"'numpy'",
",",
"collections",
"=",
"DATABASE",
".",
"stock_day",
")",
":",
"Date",
"=",
"str",
"(",
"date",
")",
"[",
"0",
":",
"10",
"]",
"if",
"QA_util_date_valid",
"(",
"Date",
")",
"is... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_index_min | 获取股票分钟线 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_index_min(
code,
start, end,
format='numpy',
frequence='1min',
collections=DATABASE.index_min):
'获取股票分钟线'
if frequence in ['1min', '1m']:
frequence = '1min'
elif frequence in ['5min', '5m']:
frequence = '5min'
elif frequence in ['15min', '15m']:
frequence = '15min'
elif frequence in ['30min', '30m']:
frequence = '30min'
elif frequence in ['60min', '60m']:
frequence = '60min'
__data = []
code = QA_util_code_tolist(code)
cursor = collections.find({
'code': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, {"_id": 0}, batch_size=10000)
if format in ['dict', 'json']:
return [data for data in cursor]
# for item in cursor:
__data = pd.DataFrame([item for item in cursor])
__data = __data.assign(datetime=pd.to_datetime(__data['datetime']))
# __data.append([str(item['code']), float(item['open']), float(item['high']), float(
# item['low']), float(item['close']), int(item['up_count']), int(item['down_count']), float(item['vol']), float(item['amount']), item['datetime'], item['time_stamp'], item['date'], item['type']])
# __data = DataFrame(__data, columns=[
# 'code', 'open', 'high', 'low', 'close', 'up_count', 'down_count', 'volume', 'amount', 'datetime', 'time_stamp', 'date', 'type'])
# __data['datetime'] = pd.to_datetime(__data['datetime'])
__data = __data.set_index('datetime', drop=False)
if format in ['numpy', 'np', 'n']:
return numpy.asarray(__data)
elif format in ['list', 'l', 'L']:
return numpy.asarray(__data).tolist()
elif format in ['P', 'p', 'pandas', 'pd']:
return __data | def QA_fetch_index_min(
code,
start, end,
format='numpy',
frequence='1min',
collections=DATABASE.index_min):
'获取股票分钟线'
if frequence in ['1min', '1m']:
frequence = '1min'
elif frequence in ['5min', '5m']:
frequence = '5min'
elif frequence in ['15min', '15m']:
frequence = '15min'
elif frequence in ['30min', '30m']:
frequence = '30min'
elif frequence in ['60min', '60m']:
frequence = '60min'
__data = []
code = QA_util_code_tolist(code)
cursor = collections.find({
'code': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, {"_id": 0}, batch_size=10000)
if format in ['dict', 'json']:
return [data for data in cursor]
# for item in cursor:
__data = pd.DataFrame([item for item in cursor])
__data = __data.assign(datetime=pd.to_datetime(__data['datetime']))
# __data.append([str(item['code']), float(item['open']), float(item['high']), float(
# item['low']), float(item['close']), int(item['up_count']), int(item['down_count']), float(item['vol']), float(item['amount']), item['datetime'], item['time_stamp'], item['date'], item['type']])
# __data = DataFrame(__data, columns=[
# 'code', 'open', 'high', 'low', 'close', 'up_count', 'down_count', 'volume', 'amount', 'datetime', 'time_stamp', 'date', 'type'])
# __data['datetime'] = pd.to_datetime(__data['datetime'])
__data = __data.set_index('datetime', drop=False)
if format in ['numpy', 'np', 'n']:
return numpy.asarray(__data)
elif format in ['list', 'l', 'L']:
return numpy.asarray(__data).tolist()
elif format in ['P', 'p', 'pandas', 'pd']:
return __data | [
"获取股票分钟线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L291-L334 | [
"def",
"QA_fetch_index_min",
"(",
"code",
",",
"start",
",",
"end",
",",
"format",
"=",
"'numpy'",
",",
"frequence",
"=",
"'1min'",
",",
"collections",
"=",
"DATABASE",
".",
"index_min",
")",
":",
"if",
"frequence",
"in",
"[",
"'1min'",
",",
"'1m'",
"]",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_future_min | 获取股票分钟线 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_future_min(
code,
start, end,
format='numpy',
frequence='1min',
collections=DATABASE.future_min):
'获取股票分钟线'
if frequence in ['1min', '1m']:
frequence = '1min'
elif frequence in ['5min', '5m']:
frequence = '5min'
elif frequence in ['15min', '15m']:
frequence = '15min'
elif frequence in ['30min', '30m']:
frequence = '30min'
elif frequence in ['60min', '60m']:
frequence = '60min'
__data = []
code = QA_util_code_tolist(code, auto_fill=False)
cursor = collections.find({
'code': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, batch_size=10000)
if format in ['dict', 'json']:
return [data for data in cursor]
for item in cursor:
__data.append([str(item['code']), float(item['open']), float(item['high']), float(
item['low']), float(item['close']), float(item['position']), float(item['price']), float(item['trade']),
item['datetime'], item['tradetime'], item['time_stamp'], item['date'], item['type']])
__data = DataFrame(__data, columns=[
'code', 'open', 'high', 'low', 'close', 'position', 'price', 'trade', 'datetime', 'tradetime', 'time_stamp', 'date', 'type'])
__data['datetime'] = pd.to_datetime(__data['datetime'])
__data = __data.set_index('datetime', drop=False)
if format in ['numpy', 'np', 'n']:
return numpy.asarray(__data)
elif format in ['list', 'l', 'L']:
return numpy.asarray(__data).tolist()
elif format in ['P', 'p', 'pandas', 'pd']:
return __data | def QA_fetch_future_min(
code,
start, end,
format='numpy',
frequence='1min',
collections=DATABASE.future_min):
'获取股票分钟线'
if frequence in ['1min', '1m']:
frequence = '1min'
elif frequence in ['5min', '5m']:
frequence = '5min'
elif frequence in ['15min', '15m']:
frequence = '15min'
elif frequence in ['30min', '30m']:
frequence = '30min'
elif frequence in ['60min', '60m']:
frequence = '60min'
__data = []
code = QA_util_code_tolist(code, auto_fill=False)
cursor = collections.find({
'code': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, batch_size=10000)
if format in ['dict', 'json']:
return [data for data in cursor]
for item in cursor:
__data.append([str(item['code']), float(item['open']), float(item['high']), float(
item['low']), float(item['close']), float(item['position']), float(item['price']), float(item['trade']),
item['datetime'], item['tradetime'], item['time_stamp'], item['date'], item['type']])
__data = DataFrame(__data, columns=[
'code', 'open', 'high', 'low', 'close', 'position', 'price', 'trade', 'datetime', 'tradetime', 'time_stamp', 'date', 'type'])
__data['datetime'] = pd.to_datetime(__data['datetime'])
__data = __data.set_index('datetime', drop=False)
if format in ['numpy', 'np', 'n']:
return numpy.asarray(__data)
elif format in ['list', 'l', 'L']:
return numpy.asarray(__data).tolist()
elif format in ['P', 'p', 'pandas', 'pd']:
return __data | [
"获取股票分钟线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L373-L416 | [
"def",
"QA_fetch_future_min",
"(",
"code",
",",
"start",
",",
"end",
",",
"format",
"=",
"'numpy'",
",",
"frequence",
"=",
"'1min'",
",",
"collections",
"=",
"DATABASE",
".",
"future_min",
")",
":",
"if",
"frequence",
"in",
"[",
"'1min'",
",",
"'1m'",
"]... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_future_list | 获取期货列表 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_future_list(collections=DATABASE.future_list):
'获取期货列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | def QA_fetch_future_list(collections=DATABASE.future_list):
'获取期货列表'
return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False) | [
"获取期货列表"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L419-L421 | [
"def",
"QA_fetch_future_list",
"(",
"collections",
"=",
"DATABASE",
".",
"future_list",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"item",
"in",
"collections",
".",
"find",
"(",
")",
"]",
")",
".",
"drop",
"(",
"'_id'",
",",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_ctp_tick | 仅供存储的ctp tick使用
Arguments:
code {[type]} -- [description]
Keyword Arguments:
format {str} -- [description] (default: {'pd'})
collections {[type]} -- [description] (default: {DATABASE.ctp_tick})
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_ctp_tick(code, start, end, frequence, format='pd', collections=DATABASE.ctp_tick):
"""仅供存储的ctp tick使用
Arguments:
code {[type]} -- [description]
Keyword Arguments:
format {str} -- [description] (default: {'pd'})
collections {[type]} -- [description] (default: {DATABASE.ctp_tick})
Returns:
[type] -- [description]
"""
code = QA_util_code_tolist(code, auto_fill=False)
cursor = collections.find({
'InstrumentID': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, {"_id": 0}, batch_size=10000)
hq = pd.DataFrame([data for data in cursor]).replace(1.7976931348623157e+308,
numpy.nan).replace('', numpy.nan).dropna(axis=1)
p1 = hq.loc[:, ['ActionDay', 'AskPrice1', 'AskVolume1', 'AveragePrice', 'BidPrice1',
'BidVolume1', 'HighestPrice', 'InstrumentID', 'LastPrice',
'OpenInterest', 'TradingDay', 'UpdateMillisec',
'UpdateTime', 'Volume']]
p1 = p1.assign(datetime=p1.ActionDay.apply(QA_util_date_int2str)+' '+p1.UpdateTime + (p1.UpdateMillisec/1000000).apply(lambda x: str('%.6f' % x)[1:]),
code=p1.InstrumentID)
p1.datetime = pd.to_datetime(p1.datetime)
return p1.set_index(p1.datetime) | def QA_fetch_ctp_tick(code, start, end, frequence, format='pd', collections=DATABASE.ctp_tick):
"""仅供存储的ctp tick使用
Arguments:
code {[type]} -- [description]
Keyword Arguments:
format {str} -- [description] (default: {'pd'})
collections {[type]} -- [description] (default: {DATABASE.ctp_tick})
Returns:
[type] -- [description]
"""
code = QA_util_code_tolist(code, auto_fill=False)
cursor = collections.find({
'InstrumentID': {'$in': code}, "time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
}, 'type': frequence
}, {"_id": 0}, batch_size=10000)
hq = pd.DataFrame([data for data in cursor]).replace(1.7976931348623157e+308,
numpy.nan).replace('', numpy.nan).dropna(axis=1)
p1 = hq.loc[:, ['ActionDay', 'AskPrice1', 'AskVolume1', 'AveragePrice', 'BidPrice1',
'BidVolume1', 'HighestPrice', 'InstrumentID', 'LastPrice',
'OpenInterest', 'TradingDay', 'UpdateMillisec',
'UpdateTime', 'Volume']]
p1 = p1.assign(datetime=p1.ActionDay.apply(QA_util_date_int2str)+' '+p1.UpdateTime + (p1.UpdateMillisec/1000000).apply(lambda x: str('%.6f' % x)[1:]),
code=p1.InstrumentID)
p1.datetime = pd.to_datetime(p1.datetime)
return p1.set_index(p1.datetime) | [
"仅供存储的ctp",
"tick使用"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L428-L459 | [
"def",
"QA_fetch_ctp_tick",
"(",
"code",
",",
"start",
",",
"end",
",",
"frequence",
",",
"format",
"=",
"'pd'",
",",
"collections",
"=",
"DATABASE",
".",
"ctp_tick",
")",
":",
"code",
"=",
"QA_util_code_tolist",
"(",
"code",
",",
"auto_fill",
"=",
"False"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_xdxr | 获取股票除权信息/数据库 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_xdxr(code, format='pd', collections=DATABASE.stock_xdxr):
'获取股票除权信息/数据库'
code = QA_util_code_tolist(code)
data = pd.DataFrame([item for item in collections.find(
{'code': {'$in': code}}, batch_size=10000)]).drop(['_id'], axis=1)
data['date'] = pd.to_datetime(data['date'])
return data.set_index('date', drop=False) | def QA_fetch_stock_xdxr(code, format='pd', collections=DATABASE.stock_xdxr):
'获取股票除权信息/数据库'
code = QA_util_code_tolist(code)
data = pd.DataFrame([item for item in collections.find(
{'code': {'$in': code}}, batch_size=10000)]).drop(['_id'], axis=1)
data['date'] = pd.to_datetime(data['date'])
return data.set_index('date', drop=False) | [
"获取股票除权信息",
"/",
"数据库"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L462-L468 | [
"def",
"QA_fetch_stock_xdxr",
"(",
"code",
",",
"format",
"=",
"'pd'",
",",
"collections",
"=",
"DATABASE",
".",
"stock_xdxr",
")",
":",
"code",
"=",
"QA_util_code_tolist",
"(",
"code",
")",
"data",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_quotations | 获取全部实时5档行情的存储结果 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_quotations(date=datetime.date.today(), db=DATABASE):
'获取全部实时5档行情的存储结果'
try:
collections = db.get_collection(
'realtime_{}'.format(date))
data = pd.DataFrame([item for item in collections.find(
{}, {"_id": 0}, batch_size=10000)])
return data.assign(date=pd.to_datetime(data.datetime.apply(lambda x: str(x)[0:10]))).assign(datetime=pd.to_datetime(data.datetime)).set_index(['datetime', 'code'], drop=False).sort_index()
except Exception as e:
raise e | def QA_fetch_quotations(date=datetime.date.today(), db=DATABASE):
'获取全部实时5档行情的存储结果'
try:
collections = db.get_collection(
'realtime_{}'.format(date))
data = pd.DataFrame([item for item in collections.find(
{}, {"_id": 0}, batch_size=10000)])
return data.assign(date=pd.to_datetime(data.datetime.apply(lambda x: str(x)[0:10]))).assign(datetime=pd.to_datetime(data.datetime)).set_index(['datetime', 'code'], drop=False).sort_index()
except Exception as e:
raise e | [
"获取全部实时5档行情的存储结果"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L524-L533 | [
"def",
"QA_fetch_quotations",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
",",
"db",
"=",
"DATABASE",
")",
":",
"try",
":",
"collections",
"=",
"db",
".",
"get_collection",
"(",
"'realtime_{}'",
".",
"format",
"(",
"date",
")",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_account | get the account
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_account(message={}, db=DATABASE):
"""get the account
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
collection = DATABASE.account
return [res for res in collection.find(message, {"_id": 0})] | def QA_fetch_account(message={}, db=DATABASE):
"""get the account
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
collection = DATABASE.account
return [res for res in collection.find(message, {"_id": 0})] | [
"get",
"the",
"account"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L536-L549 | [
"def",
"QA_fetch_account",
"(",
"message",
"=",
"{",
"}",
",",
"db",
"=",
"DATABASE",
")",
":",
"collection",
"=",
"DATABASE",
".",
"account",
"return",
"[",
"res",
"for",
"res",
"in",
"collection",
".",
"find",
"(",
"message",
",",
"{",
"\"_id\"",
":"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_risk | get the risk message
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_risk(message={}, params={"_id": 0, 'assets': 0, 'timeindex': 0, 'totaltimeindex': 0, 'benchmark_assets': 0, 'month_profit': 0}, db=DATABASE):
"""get the risk message
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
collection = DATABASE.risk
return [res for res in collection.find(message, params)] | def QA_fetch_risk(message={}, params={"_id": 0, 'assets': 0, 'timeindex': 0, 'totaltimeindex': 0, 'benchmark_assets': 0, 'month_profit': 0}, db=DATABASE):
"""get the risk message
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
collection = DATABASE.risk
return [res for res in collection.find(message, params)] | [
"get",
"the",
"risk",
"message"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L552-L565 | [
"def",
"QA_fetch_risk",
"(",
"message",
"=",
"{",
"}",
",",
"params",
"=",
"{",
"\"_id\"",
":",
"0",
",",
"'assets'",
":",
"0",
",",
"'timeindex'",
":",
"0",
",",
"'totaltimeindex'",
":",
"0",
",",
"'benchmark_assets'",
":",
"0",
",",
"'month_profit'",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_user | get the user
Arguments:
user_cookie : str the unique cookie_id for a user
Keyword Arguments:
db: database for query
Returns:
list --- [ACCOUNT] | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_user(user_cookie, db=DATABASE):
"""
get the user
Arguments:
user_cookie : str the unique cookie_id for a user
Keyword Arguments:
db: database for query
Returns:
list --- [ACCOUNT]
"""
collection = DATABASE.account
return [res for res in collection.find({'user_cookie': user_cookie}, {"_id": 0})] | def QA_fetch_user(user_cookie, db=DATABASE):
"""
get the user
Arguments:
user_cookie : str the unique cookie_id for a user
Keyword Arguments:
db: database for query
Returns:
list --- [ACCOUNT]
"""
collection = DATABASE.account
return [res for res in collection.find({'user_cookie': user_cookie}, {"_id": 0})] | [
"get",
"the",
"user"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L568-L582 | [
"def",
"QA_fetch_user",
"(",
"user_cookie",
",",
"db",
"=",
"DATABASE",
")",
":",
"collection",
"=",
"DATABASE",
".",
"account",
"return",
"[",
"res",
"for",
"res",
"in",
"collection",
".",
"find",
"(",
"{",
"'user_cookie'",
":",
"user_cookie",
"}",
",",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_strategy | get the account
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description] | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_strategy(message={}, db=DATABASE):
"""get the account
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
collection = DATABASE.strategy
return [res for res in collection.find(message, {"_id": 0})] | def QA_fetch_strategy(message={}, db=DATABASE):
"""get the account
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
collection = DATABASE.strategy
return [res for res in collection.find(message, {"_id": 0})] | [
"get",
"the",
"account"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L585-L598 | [
"def",
"QA_fetch_strategy",
"(",
"message",
"=",
"{",
"}",
",",
"db",
"=",
"DATABASE",
")",
":",
"collection",
"=",
"DATABASE",
".",
"strategy",
"return",
"[",
"res",
"for",
"res",
"in",
"collection",
".",
"find",
"(",
"message",
",",
"{",
"\"_id\"",
"... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_lhb | 获取某一天龙虎榜数据 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_lhb(date, db=DATABASE):
'获取某一天龙虎榜数据'
try:
collections = db.lhb
return pd.DataFrame([item for item in collections.find(
{'date': date}, {"_id": 0})]).set_index('code', drop=False).sort_index()
except Exception as e:
raise e | def QA_fetch_lhb(date, db=DATABASE):
'获取某一天龙虎榜数据'
try:
collections = db.lhb
return pd.DataFrame([item for item in collections.find(
{'date': date}, {"_id": 0})]).set_index('code', drop=False).sort_index()
except Exception as e:
raise e | [
"获取某一天龙虎榜数据"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L601-L608 | [
"def",
"QA_fetch_lhb",
"(",
"date",
",",
"db",
"=",
"DATABASE",
")",
":",
"try",
":",
"collections",
"=",
"db",
".",
"lhb",
"return",
"pd",
".",
"DataFrame",
"(",
"[",
"item",
"for",
"item",
"in",
"collections",
".",
"find",
"(",
"{",
"'date'",
":",
... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_financial_report | 获取专业财务报表
Arguments:
code {[type]} -- [description]
report_date {[type]} -- [description]
Keyword Arguments:
ltype {str} -- [description] (default: {'EN'})
db {[type]} -- [description] (default: {DATABASE})
Raises:
e -- [description]
Returns:
pd.DataFrame -- [description] | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_financial_report(code, report_date, ltype='EN', db=DATABASE):
"""获取专业财务报表
Arguments:
code {[type]} -- [description]
report_date {[type]} -- [description]
Keyword Arguments:
ltype {str} -- [description] (default: {'EN'})
db {[type]} -- [description] (default: {DATABASE})
Raises:
e -- [description]
Returns:
pd.DataFrame -- [description]
"""
if isinstance(code, str):
code = [code]
if isinstance(report_date, str):
report_date = [QA_util_date_str2int(report_date)]
elif isinstance(report_date, int):
report_date = [report_date]
elif isinstance(report_date, list):
report_date = [QA_util_date_str2int(item) for item in report_date]
collection = db.financial
num_columns = [item[:3] for item in list(financial_dict.keys())]
CH_columns = [item[3:] for item in list(financial_dict.keys())]
EN_columns = list(financial_dict.values())
#num_columns.extend(['283', '_id', 'code', 'report_date'])
# CH_columns.extend(['283', '_id', 'code', 'report_date'])
#CH_columns = pd.Index(CH_columns)
#EN_columns = list(financial_dict.values())
#EN_columns.extend(['283', '_id', 'code', 'report_date'])
#EN_columns = pd.Index(EN_columns)
try:
if code is not None and report_date is not None:
data = [item for item in collection.find(
{'code': {'$in': code}, 'report_date': {'$in': report_date}}, {"_id": 0}, batch_size=10000)]
elif code is None and report_date is not None:
data = [item for item in collection.find(
{'report_date': {'$in': report_date}}, {"_id": 0}, batch_size=10000)]
elif code is not None and report_date is None:
data = [item for item in collection.find(
{'code': {'$in': code}}, {"_id": 0}, batch_size=10000)]
else:
data = [item for item in collection.find({}, {"_id": 0})]
if len(data) > 0:
res_pd = pd.DataFrame(data)
if ltype in ['CH', 'CN']:
cndict = dict(zip(num_columns, CH_columns))
cndict['283'] = '283'
try:
cndict['284'] = '284'
cndict['285'] = '285'
cndict['286'] = '286'
except:
pass
cndict['code'] = 'code'
cndict['report_date'] = 'report_date'
res_pd.columns = res_pd.columns.map(lambda x: cndict[x])
elif ltype is 'EN':
endict = dict(zip(num_columns, EN_columns))
endict['283'] = '283'
try:
endict['284'] = '284'
endict['285'] = '285'
endict['286'] = '286'
except:
pass
endict['code'] = 'code'
endict['report_date'] = 'report_date'
res_pd.columns = res_pd.columns.map(lambda x: endict[x])
if res_pd.report_date.dtype == numpy.int64:
res_pd.report_date = pd.to_datetime(
res_pd.report_date.apply(QA_util_date_int2str))
else:
res_pd.report_date = pd.to_datetime(res_pd.report_date)
return res_pd.replace(-4.039810335e+34, numpy.nan).set_index(['report_date', 'code'], drop=False)
else:
return None
except Exception as e:
raise e | def QA_fetch_financial_report(code, report_date, ltype='EN', db=DATABASE):
"""获取专业财务报表
Arguments:
code {[type]} -- [description]
report_date {[type]} -- [description]
Keyword Arguments:
ltype {str} -- [description] (default: {'EN'})
db {[type]} -- [description] (default: {DATABASE})
Raises:
e -- [description]
Returns:
pd.DataFrame -- [description]
"""
if isinstance(code, str):
code = [code]
if isinstance(report_date, str):
report_date = [QA_util_date_str2int(report_date)]
elif isinstance(report_date, int):
report_date = [report_date]
elif isinstance(report_date, list):
report_date = [QA_util_date_str2int(item) for item in report_date]
collection = db.financial
num_columns = [item[:3] for item in list(financial_dict.keys())]
CH_columns = [item[3:] for item in list(financial_dict.keys())]
EN_columns = list(financial_dict.values())
#num_columns.extend(['283', '_id', 'code', 'report_date'])
# CH_columns.extend(['283', '_id', 'code', 'report_date'])
#CH_columns = pd.Index(CH_columns)
#EN_columns = list(financial_dict.values())
#EN_columns.extend(['283', '_id', 'code', 'report_date'])
#EN_columns = pd.Index(EN_columns)
try:
if code is not None and report_date is not None:
data = [item for item in collection.find(
{'code': {'$in': code}, 'report_date': {'$in': report_date}}, {"_id": 0}, batch_size=10000)]
elif code is None and report_date is not None:
data = [item for item in collection.find(
{'report_date': {'$in': report_date}}, {"_id": 0}, batch_size=10000)]
elif code is not None and report_date is None:
data = [item for item in collection.find(
{'code': {'$in': code}}, {"_id": 0}, batch_size=10000)]
else:
data = [item for item in collection.find({}, {"_id": 0})]
if len(data) > 0:
res_pd = pd.DataFrame(data)
if ltype in ['CH', 'CN']:
cndict = dict(zip(num_columns, CH_columns))
cndict['283'] = '283'
try:
cndict['284'] = '284'
cndict['285'] = '285'
cndict['286'] = '286'
except:
pass
cndict['code'] = 'code'
cndict['report_date'] = 'report_date'
res_pd.columns = res_pd.columns.map(lambda x: cndict[x])
elif ltype is 'EN':
endict = dict(zip(num_columns, EN_columns))
endict['283'] = '283'
try:
endict['284'] = '284'
endict['285'] = '285'
endict['286'] = '286'
except:
pass
endict['code'] = 'code'
endict['report_date'] = 'report_date'
res_pd.columns = res_pd.columns.map(lambda x: endict[x])
if res_pd.report_date.dtype == numpy.int64:
res_pd.report_date = pd.to_datetime(
res_pd.report_date.apply(QA_util_date_int2str))
else:
res_pd.report_date = pd.to_datetime(res_pd.report_date)
return res_pd.replace(-4.039810335e+34, numpy.nan).set_index(['report_date', 'code'], drop=False)
else:
return None
except Exception as e:
raise e | [
"获取专业财务报表",
"Arguments",
":",
"code",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"report_date",
"{",
"[",
"type",
"]",
"}",
"--",
"[",
"description",
"]",
"Keyword",
"Arguments",
":",
"ltype",
"{",
"str",
"}",
"--",
"[",
"description",
... | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L713-L801 | [
"def",
"QA_fetch_financial_report",
"(",
"code",
",",
"report_date",
",",
"ltype",
"=",
"'EN'",
",",
"db",
"=",
"DATABASE",
")",
":",
"if",
"isinstance",
"(",
"code",
",",
"str",
")",
":",
"code",
"=",
"[",
"code",
"]",
"if",
"isinstance",
"(",
"report... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
train | QA_fetch_stock_divyield | 获取股票日线 | QUANTAXIS/QAFetch/QAQuery.py | def QA_fetch_stock_divyield(code, start, end=None, format='pd', collections=DATABASE.stock_divyield):
'获取股票日线'
#code= [code] if isinstance(code,str) else code
# code checking
code = QA_util_code_tolist(code)
if QA_util_date_valid(end):
__data = []
cursor = collections.find({
'a_stockcode': {'$in': code}, "dir_dcl_date": {
"$lte": end,
"$gte": start}}, {"_id": 0}, batch_size=10000)
#res=[QA_util_dict_remove_key(data, '_id') for data in cursor]
res = pd.DataFrame([item for item in cursor])
try:
res = res.drop_duplicates(
(['dir_dcl_date', 'a_stockcode']))
res = res.ix[:, ['a_stockcode', 'a_stocksname', 'div_info', 'div_type_code', 'bonus_shr',
'cash_bt', 'cap_shr', 'epsp', 'ps_cr', 'ps_up', 'reg_date', 'dir_dcl_date',
'a_stockcode1', 'ex_divi_date', 'prg']]
except:
res = None
if format in ['P', 'p', 'pandas', 'pd']:
return res
elif format in ['json', 'dict']:
return QA_util_to_json_from_pandas(res)
# 多种数据格式
elif format in ['n', 'N', 'numpy']:
return numpy.asarray(res)
elif format in ['list', 'l', 'L']:
return numpy.asarray(res).tolist()
else:
print("QA Error QA_fetch_stock_divyield format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return None
else:
QA_util_log_info(
'QA Error QA_fetch_stock_divyield data parameter start=%s end=%s is not right' % (start, end)) | def QA_fetch_stock_divyield(code, start, end=None, format='pd', collections=DATABASE.stock_divyield):
'获取股票日线'
#code= [code] if isinstance(code,str) else code
# code checking
code = QA_util_code_tolist(code)
if QA_util_date_valid(end):
__data = []
cursor = collections.find({
'a_stockcode': {'$in': code}, "dir_dcl_date": {
"$lte": end,
"$gte": start}}, {"_id": 0}, batch_size=10000)
#res=[QA_util_dict_remove_key(data, '_id') for data in cursor]
res = pd.DataFrame([item for item in cursor])
try:
res = res.drop_duplicates(
(['dir_dcl_date', 'a_stockcode']))
res = res.ix[:, ['a_stockcode', 'a_stocksname', 'div_info', 'div_type_code', 'bonus_shr',
'cash_bt', 'cap_shr', 'epsp', 'ps_cr', 'ps_up', 'reg_date', 'dir_dcl_date',
'a_stockcode1', 'ex_divi_date', 'prg']]
except:
res = None
if format in ['P', 'p', 'pandas', 'pd']:
return res
elif format in ['json', 'dict']:
return QA_util_to_json_from_pandas(res)
# 多种数据格式
elif format in ['n', 'N', 'numpy']:
return numpy.asarray(res)
elif format in ['list', 'l', 'L']:
return numpy.asarray(res).tolist()
else:
print("QA Error QA_fetch_stock_divyield format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" " % format)
return None
else:
QA_util_log_info(
'QA Error QA_fetch_stock_divyield data parameter start=%s end=%s is not right' % (start, end)) | [
"获取股票日线"
] | QUANTAXIS/QUANTAXIS | python | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L844-L882 | [
"def",
"QA_fetch_stock_divyield",
"(",
"code",
",",
"start",
",",
"end",
"=",
"None",
",",
"format",
"=",
"'pd'",
",",
"collections",
"=",
"DATABASE",
".",
"stock_divyield",
")",
":",
"#code= [code] if isinstance(code,str) else code",
"# code checking",
"code",
"=",... | bb1fe424e4108b62a1f712b81a05cf829297a5c0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.