INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
字符串 '2018-01-01' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型float | def QA_util_date_stamp(date):
"""
字符串 '2018-01-01' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 2018-01-01 ,长度10
:return: 类型float
"""
datestr = str(date)[0:10]
date = time.mktime(time.strptime(datestr, '%Y-%m-%d'))
return date |
字符串 '2018-01-01 00:00:00' 转变成 float 类型时间 类似 time.time() 返回的类型
:param time_: 字符串str -- 数据格式 最好是%Y-%m-%d %H:%M:%S 中间要有空格
:return: 类型float | def QA_util_time_stamp(time_):
"""
字符串 '2018-01-01 00:00:00' 转变成 float 类型时间 类似 time.time() 返回的类型
:param time_: 字符串str -- 数据格式 最好是%Y-%m-%d %H:%M:%S 中间要有空格
:return: 类型float
"""
if len(str(time_)) == 10:
# yyyy-mm-dd格式
return time.mktime(time.strptime(time_, '%Y-%m-%d'))
elif l... |
datestamp转datetime
pandas转出来的timestamp是13位整数 要/1000
It’s common for this to be restricted to years from 1970 through 2038.
从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型
:param timestamp: long类型
:return: 类型float | def QA_util_stamp2datetime(timestamp):
"""
datestamp转datetime
pandas转出来的timestamp是13位整数 要/1000
It’s common for this to be restricted to years from 1970 through 2038.
从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型
:param timestamp: long类型
:return: 类型float
"""
try:
retur... |
查询数据库中的数据
:param strtime: strtime str字符串 -- 1999-12-11 这种格式
:param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Dictionary -- {'time_real': 时间,'id': id} | def QA_util_realtime(strtime, client):
"""
查询数据库中的数据
:param strtime: strtime str字符串 -- 1999-12-11 这种格式
:param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Dictionary -- {'time_real': 时间,'id': id}
"""... |
从数据库中查询 通达信时间
:param idx: 字符串 -- 数据库index
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Str -- 通达信数据库时间 | def QA_util_id2date(idx, client):
"""
从数据库中查询 通达信时间
:param idx: 字符串 -- 数据库index
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Str -- 通达信数据库时间
"""
coll = client.quantaxis.trade_date
temp_str = coll.find_o... |
判断是否是交易日
从数据库中查询
:param date: str类型 -- 1999-12-11 这种格式 10位字符串
:param code: str类型 -- 股票代码 例如 603658 , 6位字符串
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Boolean -- 是否是交易时间 | def QA_util_is_trade(date, code, client):
"""
判断是否是交易日
从数据库中查询
:param date: str类型 -- 1999-12-11 这种格式 10位字符串
:param code: str类型 -- 股票代码 例如 603658 , 6位字符串
:param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Boolean -- 是... |
quantaxis的时间选择函数,约定时间的范围,比如早上9点到11点 | def QA_util_select_hours(time=None, gt=None, lt=None, gte=None, lte=None):
'quantaxis的时间选择函数,约定时间的范围,比如早上9点到11点'
if time is None:
__realtime = datetime.datetime.now()
else:
__realtime = time
fun_list = []
if gt != None:
fun_list.append('>')
if lt != None:
fun_lis... |
'耗时长度的装饰器'
:param func:
:param args:
:param kwargs:
:return: | def QA_util_calc_time(func, *args, **kwargs):
"""
'耗时长度的装饰器'
:param func:
:param args:
:param kwargs:
:return:
"""
_time = datetime.datetime.now()
func(*args, **kwargs)
print(datetime.datetime.now() - _time) |
涨停价 | def high_limit(self):
'涨停价'
return self.groupby(level=1).close.apply(lambda x: round((x.shift(1) + 0.0002)*1.1, 2)).sort_index() |
明日跌停价 | def next_day_low_limit(self):
"明日跌停价"
return self.groupby(level=1).close.apply(lambda x: round((x + 0.0002)*0.9, 2)).sort_index() |
return medium
Keyword Arguments:
lower {[type]} -- [description] (default: {200000})
higher {[type]} -- [description] (default: {1000000})
Returns:
[type] -- [description] | def get_medium_order(self, lower=200000, higher=1000000):
"""return medium
Keyword Arguments:
lower {[type]} -- [description] (default: {200000})
higher {[type]} -- [description] (default: {1000000})
Returns:
[type] -- [description]
"""
retu... |
计算上下影线
Arguments:
data {DataStruct.slice} -- 输入的是一个行情切片
Returns:
up_shadow {float} -- 上影线
down_shdow {float} -- 下影线
entity {float} -- 实体部分
date {str} -- 时间
code {str} -- 代码 | def shadow_calc(data):
"""计算上下影线
Arguments:
data {DataStruct.slice} -- 输入的是一个行情切片
Returns:
up_shadow {float} -- 上影线
down_shdow {float} -- 下影线
entity {float} -- 实体部分
date {str} -- 时间
code {str} -- 代码
"""
up_shadow = abs(data.high - (max(data.open, da... |
标准格式是numpy | def query_data(self, code, start, end, frequence, market_type=None):
"""
标准格式是numpy
"""
try:
return self.fetcher[(market_type, frequence)](
code, start, end, frequence=frequence)
except:
pass |
掘金实现方式
save current day's stock_min data | def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
"""
掘金实现方式
save current day's stock_min data
"""
# 导入掘金模块且进行登录
try:
from gm.api import set_token
from gm.api import history
# 请自行将掘金量化的 TOKEN 替换掉 GMTOKEN
set_token("9c5601171e97994686b47b5cb... |
分钟线结构返回datetime 日线结构返回date | def datetime(self):
'分钟线结构返回datetime 日线结构返回date'
index = self.data.index.remove_unused_levels()
return pd.to_datetime(index.levels[0]) |
返回DataStruct.price的一阶差分 | def price_diff(self):
'返回DataStruct.price的一阶差分'
res = self.price.groupby(level=1).apply(lambda x: x.diff(1))
res.name = 'price_diff'
return res |
返回DataStruct.price的方差 variance | def pvariance(self):
'返回DataStruct.price的方差 variance'
res = self.price.groupby(level=1
).apply(lambda x: statistics.pvariance(x))
res.name = 'pvariance'
return res |
返回bar的涨跌幅 | def bar_pct_change(self):
'返回bar的涨跌幅'
res = (self.close - self.open) / self.open
res.name = 'bar_pct_change'
return res |
返回bar振幅 | def bar_amplitude(self):
"返回bar振幅"
res = (self.high - self.low) / self.low
res.name = 'bar_amplitude'
return res |
返回DataStruct.price的调和平均数 | def mean_harmonic(self):
'返回DataStruct.price的调和平均数'
res = self.price.groupby(level=1
).apply(lambda x: statistics.harmonic_mean(x))
res.name = 'mean_harmonic'
return res |
返回DataStruct.price的百分比变化 | def amplitude(self):
'返回DataStruct.price的百分比变化'
res = self.price.groupby(
level=1
).apply(lambda x: (x.max() - x.min()) / x.min())
res.name = 'amplitude'
return res |
返回DataStruct.close的百分比变化 | def close_pct_change(self):
'返回DataStruct.close的百分比变化'
res = self.close.groupby(level=1).apply(lambda x: x.pct_change())
res.name = 'close_pct_change'
return res |
归一化 | def normalized(self):
'归一化'
res = self.groupby('code').apply(lambda x: x / x.iloc[0])
return res |
返回一个基于代码的迭代器 | def security_gen(self):
'返回一个基于代码的迭代器'
for item in self.index.levels[1]:
yield self.new(
self.data.xs(item,
level=1,
drop_level=False),
dtype=self.type,
if_fq=self.if_fq
) |
'give the time,code tuple and turn the dict'
:param time:
:param code:
:return: 字典dict 类型 | def get_dict(self, time, code):
'''
'give the time,code tuple and turn the dict'
:param time:
:param code:
:return: 字典dict 类型
'''
try:
return self.dicts[(QA_util_to_datetime(time), str(code))]
except Exception as e:
raise e |
plot the market_data | def kline_echarts(self, code=None):
def kline_formater(param):
return param.name + ':' + vars(param)
"""plot the market_data"""
if code is None:
path_name = '.' + os.sep + 'QA_' + self.type + \
'_codepackage_' + self.if_fq + '.html'
kline = K... |
查询data | def query(self, context):
"""
查询data
"""
try:
return self.data.query(context)
except pd.core.computation.ops.UndefinedVariableError:
print('QA CANNOT QUERY THIS {}'.format(context))
pass |
仿dataframe的groupby写法,但控制了by的code和datetime
Keyword Arguments:
by {[type]} -- [description] (default: {None})
axis {int} -- [description] (default: {0})
level {[type]} -- [description] (default: {None})
as_index {bool} -- [description] (default: {True})
... | def groupby(
self,
by=None,
axis=0,
level=None,
as_index=True,
sort=False,
group_keys=False,
squeeze=False,
**kwargs
):
"""仿dataframe的groupby写法,但控制了by的code和datetime
Keyword Arguments:
... |
reindex
Arguments:
ind {[type]} -- [description]
Raises:
RuntimeError -- [description]
RuntimeError -- [description]
Returns:
[type] -- [description] | def reindex(self, ind):
"""reindex
Arguments:
ind {[type]} -- [description]
Raises:
RuntimeError -- [description]
RuntimeError -- [description]
Returns:
[type] -- [description]
"""
if isinstance(ind, pd.MultiIndex):
... |
转换DataStruct为json | def to_json(self):
"""
转换DataStruct为json
"""
data = self.data
if self.type[-3:] != 'min':
data = self.data.assign(datetime= self.datetime)
return QA_util_to_json_from_pandas(data.reset_index()) |
IO --> hdf5 | def to_hdf(self, place, name):
'IO --> hdf5'
self.data.to_hdf(place, name)
return place, name |
判断是否相同 | def is_same(self, DataStruct):
"""
判断是否相同
"""
if self.type == DataStruct.type and self.if_fq == DataStruct.if_fq:
return True
else:
return False |
将一个DataStruct按code分解为N个DataStruct | def splits(self):
"""
将一个DataStruct按code分解为N个DataStruct
"""
return list(map(lambda x: self.select_code(x), self.code)) |
QADATASTRUCT的指标/函数apply入口
Arguments:
func {[type]} -- [description]
Returns:
[type] -- [description] | def add_func(self, func, *arg, **kwargs):
"""QADATASTRUCT的指标/函数apply入口
Arguments:
func {[type]} -- [description]
Returns:
[type] -- [description]
"""
return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs) |
获取不同格式的数据
Arguments:
columns {[type]} -- [description]
Keyword Arguments:
type {str} -- [description] (default: {'ndarray'})
with_index {bool} -- [description] (default: {False})
Returns:
[type] -- [description] | def get_data(self, columns, type='ndarray', with_index=False):
"""获取不同格式的数据
Arguments:
columns {[type]} -- [description]
Keyword Arguments:
type {str} -- [description] (default: {'ndarray'})
with_index {bool} -- [description] (default: {False})
Retu... |
增加对于多列的支持 | def pivot(self, column_):
"""增加对于多列的支持"""
if isinstance(column_, str):
try:
return self.data.reset_index().pivot(
index='datetime',
columns='code',
values=column_
)
except:
... |
选择code,start,end
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
... | def selects(self, code, start, end=None):
"""
选择code,start,end
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间... |
选择起始时间
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢... | def select_time(self, start, end=None):
"""
选择起始时间
如果end不填写,默认获取到结尾
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,rais... |
选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description] | def select_day(self, day):
"""选取日期(一般用于分钟线)
Arguments:
day {[type]} -- [description]
Raises:
ValueError -- [description]
Returns:
[type] -- [description]
"""
def _select_day(day):
return self.data.loc[day, slice(None)]
... |
选择月份
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复 | def select_month(self, month):
"""
选择月份
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pa... |
选择股票
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pandas索引问题已经解决
全部恢复 | def select_code(self, code):
"""
选择股票
@2018/06/03 pandas 的索引问题导致
https://github.com/pandas-dev/pandas/issues/21299
因此先用set_index去重做一次index
影响的有selects,select_time,select_month,get_bar
@2018/06/04
当选择的时间越界/股票不存在,raise ValueError
@2018/06/04 pand... |
获取一个bar的数据
返回一个series
如果不存在,raise ValueError | def get_bar(self, code, time):
"""
获取一个bar的数据
返回一个series
如果不存在,raise ValueError
"""
try:
return self.data.loc[(pd.Timestamp(time), code)]
except:
raise ValueError(
'DATASTRUCT CURRENTLY CANNOT FIND THIS BAR WITH {} {}'.forma... |
将天软本地数据导入 QA 数据库
:param client:
:param ui_log:
:param ui_progress:
:param data_path: 存放天软数据的路径,默认文件名格式为类似 "SH600000.csv" 格式 | def QA_SU_trans_stock_min(client=DATABASE, ui_log=None, ui_progress=None,
data_path: str = "D:\\skysoft\\", type_="1min"):
"""
将天软本地数据导入 QA 数据库
:param client:
:param ui_log:
:param ui_progress:
:param data_path: 存放天软数据的路径,默认文件名格式为类似 "SH600000.csv" 格式
"""
code_li... |
用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip
默认使用特定品种1min的方式的获取 | def get_best_ip_by_real_data_fetch(_type='stock'):
"""
用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip
默认使用特定品种1min的方式的获取
"""
from QUANTAXIS.QAUtil.QADate import QA_util_today_str
import time
#找到前两天的有效交易日期
pre_trade_date=QA_util_get_real_date(QA_util_today_str())
pre_trade_date=QA_util_get... |
根据ping排序返回可用的ip列表
2019 03 31 取消参数filename
:param ip_list: ip列表
:param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip
:param _type: ip类型
:return: 可以ping通的ip列表 | def get_ip_list_by_multi_process_ping(ip_list=[], n=0, _type='stock'):
''' 根据ping排序返回可用的ip列表
2019 03 31 取消参数filename
:param ip_list: ip列表
:param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip
:param _type: ip类型
:return: 可以ping通的ip列表
'''
cache = QA_util_cache()
results = cache.get(... |
[summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description] | def get_mainmarket_ip(ip, port):
"""[summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description]
"""
global best_ip
if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is No... |
按bar长度推算数据
Arguments:
code {[type]} -- [description]
_type {[type]} -- [description]
lens {[type]} -- [description]
Keyword Arguments:
ip {[type]} -- [description] (default: {best_ip})
port {[type]} -- [description] (default: {7709})
Returns:
[type] -- [des... | def QA_fetch_get_security_bars(code, _type, lens, ip=None, port=None):
"""按bar长度推算数据
Arguments:
code {[type]} -- [description]
_type {[type]} -- [description]
lens {[type]} -- [description]
Keyword Arguments:
ip {[type]} -- [description] (default: {best_ip})
port {[... |
获取日线及以上级别的数据
Arguments:
code {str:6} -- code 是一个单独的code 6位长度的str
start_date {str:10} -- 10位长度的日期 比如'2017-01-01'
end_date {str:10} -- 10位长度的日期 比如'2018-01-01'
Keyword Arguments:
if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhf... | def QA_fetch_get_stock_day(code, start_date, end_date, if_fq='00', frequence='day', ip=None, port=None):
"""获取日线及以上级别的数据
Arguments:
code {str:6} -- code 是一个单独的code 6位长度的str
start_date {str:10} -- 10位长度的日期 比如'2017-01-01'
end_date {str:10} -- 10位长度的日期 比如'2018-01-01'
Keyword Argument... |
深市代码分类
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description] | def for_sz(code):
"""深市代码分类
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description]
"""
if str(code)[0:2] in ['00', '30', '02']:
return 'stock_cn'
elif str(code)[0:2] in ['39']:
return 'index_cn'
elif str(code)[0:2] in ['15']:
ret... |
获取指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
Returns:
[type] -- [description] | def QA_fetch_get_index_list(ip=None, port=None):
"""获取指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
"""
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
... |
实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前 | def QA_fetch_get_stock_transaction_realtime(code, ip=None, port=None):
'实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
try:
with api.connect(ip, port):
data = pd.DataFrame()
data = pd.concat([api.to_df(api.get_transa... |
除权除息 | 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': '股本变化',
... |
股票基本信息 | def QA_fetch_get_stock_info(code, ip=None, port=None):
'股票基本信息'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
market_code = _select_market_code(code)
with api.connect(ip, port):
return api.to_df(api.get_finance_info(market_code, code)) |
板块数据 | def QA_fetch_get_stock_block(ip=None, port=None):
'板块数据'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat([api.to_df(api.get_and_parse_block_info("block_gn.dat")).assign(type='gn'),
api.to_df(api.get_and_parse_block_... |
期货代码list | def QA_fetch_get_extensionmarket_list(ip=None, port=None):
'期货代码list'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
with apix.connect(ip, port):
num = apix.get_instrument_count()
return pd.concat([apix.to_df(
apix.get_instrument_info((int(num / 500) - i) * ... |
[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 ... | 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
... |
全球指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
37 11 全球指数(静态) FW
12 5 国际指数 WI | def QA_fetch_get_globalindex_list(ip=None, port=None):
"""全球指数列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
37 11 全球指数(静态) FW
12 5 国际指数 WI
"""
global extension_m... |
[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 ... | 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
... |
[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 香港基金 ... | 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... |
[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... | 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 纽约商... |
[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 香港基金 ... | 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... |
[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 香港基... | 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 ... |
[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 美股 USA STOCK
74 13 美国股票 US
40 11 中国概念股 CH
41 11 美股知名公司 MG | def QA_fetch_get_usstock_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 美股 USA STOCK
74 13 美国股票 US
40 11 中国概念股 CH
41 ... |
宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG | def QA_fetch_get_macroindex_list(ip=None, port=None):
"""宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG
"""
global extension_market_list
extension_market_list = QA... |
期权列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 期权 OPTION
1 12 临时期权(主要是50ETF)
4 12 郑州商品期权 OZ
5 12 大连商品期权 OD
6 12 上海... | def QA_fetch_get_option_list(ip=None, port=None):
"""期权列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 期权 OPTION
1 12 临时期权(主要是50ETF)
4 12 郑州商品期权 OZ
5 ... |
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series | def QA_fetch_get_option_contract_time_to_market():
'''
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
'''
fix here :
See the caveats in the documentation: http://panda... |
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series | def QA_fetch_get_option_50etf_contract_time_to_market():
'''
#🛠todo 获取期权合约的上市日期 ? 暂时没有。
:return: list Series
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
'''
fix here :
See the caveats in the documenta... |
铜期权 CU 开头 上期证
豆粕 M开头 大商所
白糖 SR开头 郑商所
测试中发现,行情不太稳定 ? 是 通达信 IP 的问题 ? | def QA_fetch_get_commodity_option_CF_contract_time_to_market():
'''
铜期权 CU 开头 上期证
豆粕 M开头 大商所
白糖 SR开头 郑商所
测试中发现,行情不太稳定 ? 是 通达信 IP 的问题 ?
'''
result = QA_fetch_get_option_list('tdx')
# pprint.pprint(result)
# category market code name desc code
# df = pd.DataFra... |
汇率列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 汇率 EXCHANGERATE
10 4 基本汇率 FE
11 4 交叉汇率 FX | def QA_fetch_get_exchangerate_list(ip=None, port=None):
"""汇率列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
## 汇率 EXCHANGERATE
10 4 基本汇率 FE
11 4 交叉汇率 FX
""... |
期货数据 日线 | 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 e... |
期货数据 分钟线 | 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... |
期货历史成交分笔 | 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 extensio... |
期货历史成交分笔 | 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_lis... |
期货实时价格 | 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.concat 用于合并一个list里面的多个DataStruct,会自动去重
Arguments:
lists {[type]} -- [DataStruct1,DataStruct2,....,DataStructN]
Returns:
[type] -- new DataStruct | def concat(lists):
"""类似于pd.concat 用于合并一个list里面的多个DataStruct,会自动去重
Arguments:
lists {[type]} -- [DataStruct1,DataStruct2,....,DataStructN]
Returns:
[type] -- new DataStruct
"""
return lists[0].new(
pd.concat([lists.data for lists in lists]).drop_duplicates()
) |
dataframe from tushare
Arguments:
dataframe {[type]} -- [description]
Returns:
[type] -- [description] | def from_tushare(dataframe, dtype='day'):
"""dataframe from tushare
Arguments:
dataframe {[type]} -- [description]
Returns:
[type] -- [description]
"""
if dtype in ['day']:
return QA_DataStruct_Stock_day(
dataframe.assign(date=pd.to_datetime(dataframe.date)
... |
日线QDS装饰器 | def QDS_StockDayWarpper(func):
"""
日线QDS装饰器
"""
def warpper(*args, **kwargs):
data = func(*args, **kwargs)
if isinstance(data.index, pd.MultiIndex):
return QA_DataStruct_Stock_day(data)
else:
return QA_DataStruct_Stock_day(
data.assign(d... |
分钟线QDS装饰器 | def QDS_StockMinWarpper(func, *args, **kwargs):
"""
分钟线QDS装饰器
"""
def warpper(*args, **kwargs):
data = func(*args, **kwargs)
if isinstance(data.index, pd.MultiIndex):
return QA_DataStruct_Stock_min(data)
else:
return QA_DataStruct_Stock_min(
... |
获取股票的复权因子
Arguments:
code {[type]} -- [description]
Keyword Arguments:
end {str} -- [description] (default: {''})
Returns:
[type] -- [description] | def QA_fetch_get_stock_adj(code, end=''):
"""获取股票的复权因子
Arguments:
code {[type]} -- [description]
Keyword Arguments:
end {str} -- [description] (default: {''})
Returns:
[type] -- [description]
"""
pro = get_pro()
adj = pro.adj_factor(ts_code=code, trade... |
字符串 '20180101' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 20180101 ,长度8
:return: 类型float | def cover_time(date):
"""
字符串 '20180101' 转变成 float 类型时间 类似 time.time() 返回的类型
:param date: 字符串str -- 格式必须是 20180101 ,长度8
:return: 类型float
"""
datestr = str(date)[0:8]
date = time.mktime(time.strptime(datestr, '%Y%m%d'))
return date |
通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description] | def new(self, data):
"""通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description]
"""
temp = copy(self)
temp.__init__(data)
return temp |
按股票排列的查看blockname的视图
Returns:
[type] -- [description] | def view_code(self):
"""按股票排列的查看blockname的视图
Returns:
[type] -- [description]
"""
return self.data.groupby(level=1).apply(
lambda x:
[item for item in x.index.remove_unused_levels().levels[0]]
) |
getcode 获取某一只股票的板块
Arguments:
code {str} -- 股票代码
Returns:
DataStruct -- [description] | def get_code(self, code):
"""getcode 获取某一只股票的板块
Arguments:
code {str} -- 股票代码
Returns:
DataStruct -- [description]
"""
# code= [code] if isinstance(code,str) else
return self.new(self.data.loc[(slice(None), code), :]) |
getblock 获取板块, block_name是list或者是单个str
Arguments:
block_name {[type]} -- [description]
Returns:
[type] -- [description] | def get_block(self, block_name):
"""getblock 获取板块, block_name是list或者是单个str
Arguments:
block_name {[type]} -- [description]
Returns:
[type] -- [description]
"""
# block_name = [block_name] if isinstance(
# block_name, str) else block_name
... |
get_both_code 获取几个股票相同的版块
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description] | def get_both_code(self, code):
"""get_both_code 获取几个股票相同的版块
Arguments:
code {[type]} -- [description]
Returns:
[type] -- [description]
"""
return self.new(self.data.loc[(slice(None), code), :]) |
统一的获取期货/股票tick的接口 | def QA_get_tick(code, start, end, market):
"""
统一的获取期货/股票tick的接口
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
res = QATdx.QA_fetch_get_stock_transaction(code, start, end)
elif market == MARKET_TYPE.FUTURE_CN:
res = QATdx.QA_fetch_get_future_transaction(code, start, end)
... |
统一的获取期货/股票实时行情的接口 | def QA_get_realtime(code, market):
"""
统一的获取期货/股票实时行情的接口
"""
res = None
if market == MARKET_TYPE.STOCK_CN:
res = QATdx.QA_fetch_get_stock_realtime(code)
elif market == MARKET_TYPE.FUTURE_CN:
res = QATdx.QA_fetch_get_future_realtime(code)
return res |
一个统一的获取k线的方法
如果使用mongo,从本地数据库获取,失败则在线获取
Arguments:
code {str/list} -- 期货/股票的代码
start {str} -- 开始日期
end {str} -- 结束日期
frequence {enum} -- 频率 QA.FREQUENCE
market {enum} -- 市场 QA.MARKET_TYPE
source {enum} -- 来源 QA.DATASOURCE
output {enum} -- 输出类型 QA.OUTPUT_F... | 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
m... |
随机生成股票代码
:param stockNumber: 生成个数
:return: ['60XXXX', '00XXXX', '300XXX'] | def QA_util_random_with_zh_stock_code(stockNumber=10):
'''
随机生成股票代码
:param stockNumber: 生成个数
:return: ['60XXXX', '00XXXX', '300XXX']
'''
codeList = []
pt = 0
for i in range(stockNumber):
if pt == 0:
#print("random 60XXXX")
iCode = random.randint(600000, 6... |
生成account随机值
Acc+4数字id+4位大小写随机 | def QA_util_random_with_topic(topic='Acc', lens=8):
"""
生成account随机值
Acc+4数字id+4位大小写随机
"""
_list = [chr(i) for i in range(65,
91)] + [chr(i) for i in range(97,
123)
... |
支持股票/期货的更新仓位
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
... | 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
... |
收盘后的结算事件 | def settle(self):
"""收盘后的结算事件
"""
self.volume_long_his += self.volume_long_today
self.volume_long_today = 0
self.volume_long_frozen_today = 0
self.volume_short_his += self.volume_short_today
self.volume_short_today = 0
self.volume_short_frozen_today = 0 |
可平仓数量
Returns:
[type] -- [description] | def close_available(self):
"""可平仓数量
Returns:
[type] -- [description]
"""
return {
'volume_long': self.volume_long - self.volume_long_frozen,
'volume_short': self.volume_short - self.volume_short_frozen
} |
委托回报 | def orderAction(self, order:QA_Order):
"""
委托回报
"""
return self.pms[order.code][order.order_id].receive_order(order) |
聚宽实现方式
save current day's stock_min data | def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
"""
聚宽实现方式
save current day's stock_min data
"""
# 导入聚宽模块且进行登录
try:
import jqdatasdk
# 请自行将 JQUSERNAME 和 JQUSERPASSWD 修改为自己的账号密码
jqdatasdk.auth("JQUSERNAME", "JQUSERPASSWD")
except:
rais... |
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 paramet... | 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, otherw... |
使用数据库数据计算复权 | 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_afte... |
1.DIF向上突破DEA,买入信号参考。
2.DIF向下跌破DEA,卖出信号参考。 | def MACD_JCSC(dataframe, SHORT=12, LONG=26, M=9):
"""
1.DIF向上突破DEA,买入信号参考。
2.DIF向下跌破DEA,卖出信号参考。
"""
CLOSE = dataframe.close
DIFF = QA.EMA(CLOSE, SHORT) - QA.EMA(CLOSE, LONG)
DEA = QA.EMA(DIFF, M)
MACD = 2*(DIFF-DEA)
CROSS_JC = QA.CROSS(DIFF, DEA)
CROSS_SC = QA.CROSS(DEA, DIFF)
... |
Create the tables needed to store the information. | def _create(self, cache_file):
"""Create the tables needed to store the information."""
conn = sqlite3.connect(cache_file)
cur = conn.cursor()
cur.execute("PRAGMA foreign_keys = ON")
cur.execute('''
CREATE TABLE jobs(
hash TEXT NOT NULL UNIQUE PRIMARY ... |
Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise | def get(self, id):
"""Retrieves the job with the selected ID.
:param str id: The ID of the job
:returns: The dictionary of the job if found, None otherwise
"""
self.cur.execute("SELECT * FROM jobs WHERE hash=?", (id,))
item = self.cur.fetchone()
if item:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.