Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def QA_indicator_MIKE(DataFrame, N=12):
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
TYP = (HIGH+LOW+CLOSE)/3
LL = LLV(LOW, N)
HH = HHV(HIGH, N)
WR = TYP+(TYP-LL)
MR = TYP+(HH-LL)
SR = 2*HH-LL
WS = TYP-(HH-TYP)
MS = TYP-(HH-LL)
SS = 2*LL-HH
return pd.DataFrame({
'WR': WR, 'MR': MR, 'SR': SR,
'WS': WS, 'MS': MS, 'SS': SS
})
|
[
"\n MIKE指标\n 指标说明\n MIKE是另外一种形式的路径指标。\n 买卖原则\n 1 WEAK-S,MEDIUM-S,STRONG-S三条线代表初级、中级、强力支撑。\n 2 WEAK-R,MEDIUM-R,STRONG-R三条线代表初级、中级、强力压力。\n "
] |
Please provide a description of the function:def QA_indicator_BBI(DataFrame, N1=3, N2=6, N3=12, N4=24):
'多空指标'
C = DataFrame['close']
bbi = (MA(C, N1) + MA(C, N2) + MA(C, N3) + MA(C, N4)) / 4
DICT = {'BBI': bbi}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_MFI(DataFrame, N=14):
C = DataFrame['close']
H = DataFrame['high']
L = DataFrame['low']
VOL = DataFrame['volume']
TYP = (C + H + L) / 3
V1 = SUM(IF(TYP > REF(TYP, 1), TYP * VOL, 0), N) / \
SUM(IF(TYP < REF(TYP, 1), TYP * VOL, 0), N)
mfi = 100 - (100 / (1 + V1))
DICT = {'MFI': mfi}
return pd.DataFrame(DICT)
|
[
"\n 资金指标\n TYP := (HIGH + LOW + CLOSE)/3;\n V1:=SUM(IF(TYP>REF(TYP,1),TYP*VOL,0),N)/SUM(IF(TYP<REF(TYP,1),TYP*VOL,0),N);\n MFI:100-(100/(1+V1));\n 赋值: (最高价 + 最低价 + 收盘价)/3\n V1赋值:如果TYP>1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和/如果TYP<1日前的TYP,返回TYP*成交量(手),否则返回0的N日累和\n 输出资金流量指标:100-(100/(1+V1))\n "
] |
Please provide a description of the function:def QA_indicator_ATR(DataFrame, N=14):
C = DataFrame['close']
H = DataFrame['high']
L = DataFrame['low']
TR = MAX(MAX((H - L), ABS(REF(C, 1) - H)), ABS(REF(C, 1) - L))
atr = MA(TR, N)
return pd.DataFrame({'TR': TR, 'ATR': atr})
|
[
"\n 输出TR:(最高价-最低价)和昨收-最高价的绝对值的较大值和昨收-最低价的绝对值的较大值\n 输出真实波幅:TR的N日简单移动平均\n 算法:今日振幅、今日最高与昨收差价、今日最低与昨收差价中的最大值,为真实波幅,求真实波幅的N日移动平均\n\n 参数:N 天数,一般取14\n\n "
] |
Please provide a description of the function:def QA_indicator_SKDJ(DataFrame, N=9, M=3):
CLOSE = DataFrame['close']
LOWV = LLV(DataFrame['low'], N)
HIGHV = HHV(DataFrame['high'], N)
RSV = EMA((CLOSE - LOWV) / (HIGHV - LOWV) * 100, M)
K = EMA(RSV, M)
D = MA(K, M)
DICT = {'RSV': RSV, 'SKDJ_K': K, 'SKDJ_D': D}
return pd.DataFrame(DICT)
|
[
"\n 1.指标>80 时,回档机率大;指标<20 时,反弹机率大;\n 2.K在20左右向上交叉D时,视为买进信号参考; \n 3.K在80左右向下交叉D时,视为卖出信号参考;\n 4.SKDJ波动于50左右的任何讯号,其作用不大。\n\n "
] |
Please provide a description of the function:def QA_indicator_DDI(DataFrame, N=13, N1=26, M=1, M1=5):
H = DataFrame['high']
L = DataFrame['low']
DMZ = IF((H + L) > (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
DMF = IF((H + L) < (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
DIZ = SUM(DMZ, N) / (SUM(DMZ, N) + SUM(DMF, N))
DIF = SUM(DMF, N) / (SUM(DMF, N) + SUM(DMZ, N))
ddi = DIZ - DIF
ADDI = SMA(ddi, N1, M)
AD = MA(ADDI, M1)
DICT = {'DDI': ddi, 'ADDI': ADDI, 'AD': AD}
return pd.DataFrame(DICT)
|
[
"\n '方向标准离差指数'\n 分析DDI柱状线,由红变绿(正变负),卖出信号参考;由绿变红,买入信号参考。\n "
] |
Please provide a description of the function:def QA_indicator_shadow(DataFrame):
return {
'LOW': lower_shadow(DataFrame), 'UP': upper_shadow(DataFrame),
'BODY': body(DataFrame), 'BODY_ABS': body_abs(DataFrame), 'PRICE_PCG': price_pcg(DataFrame)
}
|
[
"\n 上下影线指标\n "
] |
Please provide a description of the function:def run(self, series, exponent=None):
'''
:type series: List
:type exponent: int
:rtype: float
'''
try:
return self.calculateHurst(series, exponent)
except Exception as e:
print(" Error: %s" % e)
|
[] |
Please provide a description of the function:def bestExponent(self, seriesLenght):
'''
:type seriesLenght: int
:rtype: int
'''
i = 0
cont = True
while(cont):
if(int(seriesLenght/int(math.pow(2, i))) <= 1):
cont = False
else:
i += 1
return int(i-1)
|
[] |
Please provide a description of the function:def mean(self, series, start, limit):
'''
:type start: int
:type limit: int
:rtype: float
'''
return float(np.mean(series[start:limit]))
|
[] |
Please provide a description of the function:def deviation(self, series, start, limit, mean):
'''
:type start: int
:type limit: int
:type mean: int
:rtype: list()
'''
d = []
for x in range(start, limit):
d.append(float(series[x] - mean))
return d
|
[] |
Please provide a description of the function:def standartDeviation(self, series, start, limit):
'''
:type start: int
:type limit: int
:rtype: float
'''
return float(np.std(series[start:limit]))
|
[] |
Please provide a description of the function:def calculateHurst(self, series, exponent=None):
'''
:type series: List
:type exponent: int
:rtype: float
'''
rescaledRange = list()
sizeRange = list()
rescaledRangeMean = list()
if(exponent is None):
exponent = self.bestExponent(len(series))
for i in range(0, exponent):
partsNumber = int(math.pow(2, i))
size = int(len(series)/partsNumber)
sizeRange.append(size)
rescaledRange.append(0)
rescaledRangeMean.append(0)
for x in range(0, partsNumber):
start = int(size*(x))
limit = int(size*(x+1))
deviationAcumulative = self.sumDeviation(self.deviation(
series, start, limit, self.mean(series, start, limit)))
deviationsDifference = float(
max(deviationAcumulative) - min(deviationAcumulative))
standartDeviation = self.standartDeviation(
series, start, limit)
if(deviationsDifference != 0 and standartDeviation != 0):
rescaledRange[i] += (deviationsDifference /
standartDeviation)
y = 0
for x in rescaledRange:
rescaledRangeMean[y] = x/int(math.pow(2, y))
y = y+1
# log calculation
rescaledRangeLog = list()
sizeRangeLog = list()
for i in range(0, exponent):
rescaledRangeLog.append(math.log(rescaledRangeMean[i], 10))
sizeRangeLog.append(math.log(sizeRange[i], 10))
slope, intercept = np.polyfit(sizeRangeLog, rescaledRangeLog, 1)
ablineValues = [slope * i + intercept for i in sizeRangeLog]
plt.plot(sizeRangeLog, rescaledRangeLog, '--')
plt.plot(sizeRangeLog, ablineValues, 'b')
plt.title(slope)
# graphic dimension settings
limitUp = 0
if(max(sizeRangeLog) > max(rescaledRangeLog)):
limitUp = max(sizeRangeLog)
else:
limitUp = max(rescaledRangeLog)
limitDown = 0
if(min(sizeRangeLog) > min(rescaledRangeLog)):
limitDown = min(rescaledRangeLog)
else:
limitDown = min(sizeRangeLog)
plt.gca().set_xlim(limitDown, limitUp)
plt.gca().set_ylim(limitDown, limitUp)
print("Hurst exponent: " + str(slope))
plt.show()
return slope
|
[] |
Please provide a description of the function:def QA_util_send_mail(msg, title, from_user, from_password, to_addr, smtp):
msg = MIMEText(msg, 'plain', 'utf-8')
msg['Subject'] = Header(title, 'utf-8').encode()
server = smtplib.SMTP(smtp, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_user, from_password)
server.sendmail(from_user, [to_addr], msg.as_string())
|
[
"邮件发送\n \n Arguments:\n msg {[type]} -- [description]\n title {[type]} -- [description]\n from_user {[type]} -- [description]\n from_password {[type]} -- [description]\n to_addr {[type]} -- [description]\n smtp {[type]} -- [description]\n "
] |
Please provide a description of the function:def QA_fetch_get_stock_analysis(code):
market = 'sh' if _select_market_code(code) == 1 else 'sz'
null = 'none'
data = eval(requests.get(BusinessAnalysis_url.format(
market, code), headers=headers_em).text)
zyfw = pd.DataFrame(data.get('zyfw', None))
jyps = pd.DataFrame(data.get('jyps', None))
zygcfx = data.get('zygcfx', [])
temp = []
for item in zygcfx:
try:
data_ = pd.concat([pd.DataFrame(item['hy']).assign(date=item['rq']).assign(classify='hy'),
pd.DataFrame(item['cp']).assign(
date=item['rq']).assign(classify='cp'),
pd.DataFrame(item['qy']).assign(date=item['rq']).assign(classify='qy')])
temp.append(data_)
except:
pass
try:
res_zyfcfx = pd.concat(temp).set_index(
['date', 'classify'], drop=False)
except:
res_zyfcfx = None
return zyfw, jyps, res_zyfcfx
|
[
"\n 'zyfw', 主营范围 'jyps'#经营评述 'zygcfx' 主营构成分析\n\n date 主营构成\t主营收入(元)\t收入比例cbbl\t主营成本(元)\t成本比例\t主营利润(元)\t利润比例\t毛利率(%)\n 行业 /产品/ 区域 hq cp qy\n "
] |
Please provide a description of the function:def send_order(self, code, price, amount, towards, order_model, market=None):
towards = 0 if towards == ORDER_DIRECTION.BUY else 1
if order_model == ORDER_MODEL.MARKET:
order_model = 4
elif order_model == ORDER_MODEL.LIMIT:
order_model = 0
if market is None:
market = QAFetch.base.get_stock_market(code)
if not isinstance(market, str):
raise Exception('%s不正确,请检查code和market参数' % market)
market = market.lower()
if market not in ['sh', 'sz']:
raise Exception('%s不支持,请检查code和market参数' % market)
return self.data_to_df(self.call("send_order", {
'client_id': self.client_id,
'category': towards,
'price_type': order_model,
'gddm': self.gddm_sh if market == 'sh' else self.gddm_sz,
'zqdm': code,
'price': price,
'quantity': amount
}))
|
[
"下单\n\n Arguments:\n code {[type]} -- [description]\n price {[type]} -- [description]\n amount {[type]} -- [description]\n towards {[type]} -- [description]\n order_model {[type]} -- [description]\n market:市场,SZ 深交所,SH 上交所\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_util_getBetweenMonth(from_date, to_date):
date_list = {}
begin_date = datetime.datetime.strptime(from_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(to_date, "%Y-%m-%d")
while begin_date <= end_date:
date_str = begin_date.strftime("%Y-%m")
date_list[date_str] = ['%d-%d-01' % (begin_date.year, begin_date.month),
'%d-%d-%d' % (begin_date.year, begin_date.month,
calendar.monthrange(begin_date.year, begin_date.month)[1])]
begin_date = QA_util_get_1st_of_next_month(begin_date)
return(date_list)
|
[
"\n #返回所有月份,以及每月的起始日期、结束日期,字典格式\n "
] |
Please provide a description of the function:def QA_util_add_months(dt, months):
dt = datetime.datetime.strptime(
dt, "%Y-%m-%d") + relativedelta(months=months)
return(dt)
|
[
"\n #返回dt隔months个月后的日期,months相当于步长\n "
] |
Please provide a description of the function:def QA_util_get_1st_of_next_month(dt):
year = dt.year
month = dt.month
if month == 12:
month = 1
year += 1
else:
month += 1
res = datetime.datetime(year, month, 1)
return res
|
[
"\n 获取下个月第一天的日期\n :return: 返回日期\n "
] |
Please provide a description of the function:def QA_util_getBetweenQuarter(begin_date, end_date):
quarter_list = {}
month_list = QA_util_getBetweenMonth(begin_date, end_date)
for value in month_list:
tempvalue = value.split("-")
year = tempvalue[0]
if tempvalue[1] in ['01', '02', '03']:
quarter_list[year + "Q1"] = ['%s-01-01' % year, '%s-03-31' % year]
elif tempvalue[1] in ['04', '05', '06']:
quarter_list[year + "Q2"] = ['%s-04-01' % year, '%s-06-30' % year]
elif tempvalue[1] in ['07', '08', '09']:
quarter_list[year + "Q3"] = ['%s-07-31' % year, '%s-09-30' % year]
elif tempvalue[1] in ['10', '11', '12']:
quarter_list[year + "Q4"] = ['%s-10-01' % year, '%s-12-31' % year]
return(quarter_list)
|
[
"\n #加上每季度的起始日期、结束日期\n "
] |
Please provide a description of the function:def save_account(message, collection=DATABASE.account):
try:
collection.create_index(
[("account_cookie", ASCENDING), ("user_cookie", ASCENDING), ("portfolio_cookie", ASCENDING)], unique=True)
except:
pass
collection.update(
{'account_cookie': message['account_cookie'], 'portfolio_cookie':
message['portfolio_cookie'], 'user_cookie': message['user_cookie']},
{'$set': message},
upsert=True
)
|
[
"save account\n\n Arguments:\n message {[type]} -- [description]\n\n Keyword Arguments:\n collection {[type]} -- [description] (default: {DATABASE})\n "
] |
Please provide a description of the function:def QA_SU_save_financial_files():
download_financialzip()
coll = DATABASE.financial
coll.create_index(
[("code", ASCENDING), ("report_date", ASCENDING)], unique=True)
for item in os.listdir(download_path):
if item[0:4] != 'gpcw':
print(
"file ", item, " is not start with gpcw , seems not a financial file , ignore!")
continue
date = int(item.split('.')[0][-8:])
print('QUANTAXIS NOW SAVING {}'.format(date))
if coll.find({'report_date': date}).count() < 3600:
print(coll.find({'report_date': date}).count())
data = QA_util_to_json_from_pandas(parse_filelist([item]).reset_index(
).drop_duplicates(subset=['code', 'report_date']).sort_index())
# data["crawl_date"] = str(datetime.date.today())
try:
coll.insert_many(data, ordered=False)
except Exception as e:
if isinstance(e, MemoryError):
coll.insert_many(data, ordered=True)
elif isinstance(e, pymongo.bulk.BulkWriteError):
pass
else:
print('ALL READY IN DATABASE')
print('SUCCESSFULLY SAVE/UPDATE FINANCIAL DATA')
|
[
"本地存储financialdata\n "
] |
Please provide a description of the function:def QA_util_log_info(
logs,
ui_log=None,
ui_progress=None,
ui_progress_int_value=None,
):
logging.warning(logs)
# 给GUI使用,更新当前任务到日志和进度
if ui_log is not None:
if isinstance(logs, str):
ui_log.emit(logs)
if isinstance(logs, list):
for iStr in logs:
ui_log.emit(iStr)
if ui_progress is not None and ui_progress_int_value is not None:
ui_progress.emit(ui_progress_int_value)
|
[
"\n QUANTAXIS Log Module\n @yutiansut\n\n QA_util_log_x is under [QAStandard#0.0.2@602-x] Protocol\n "
] |
Please provide a description of the function:def QA_save_tdx_to_mongo(file_dir, client=DATABASE):
reader = TdxMinBarReader()
__coll = client.stock_min_five
for a, v, files in os.walk(file_dir):
for file in files:
if (str(file)[0:2] == 'sh' and int(str(file)[2]) == 6) or \
(str(file)[0:2] == 'sz' and int(str(file)[2]) == 0) or \
(str(file)[0:2] == 'sz' and int(str(file)[2]) == 3):
QA_util_log_info('Now_saving ' + str(file)
[2:8] + '\'s 5 min tick')
fname = file_dir + os.sep + file
df = reader.get_df(fname)
df['code'] = str(file)[2:8]
df['market'] = str(file)[0:2]
df['datetime'] = [str(x) for x in list(df.index)]
df['date'] = [str(x)[0:10] for x in list(df.index)]
df['time_stamp'] = df['datetime'].apply(
lambda x: QA_util_time_stamp(x))
df['date_stamp'] = df['date'].apply(
lambda x: QA_util_date_stamp(x))
data_json = json.loads(df.to_json(orient='records'))
__coll.insert_many(data_json)
|
[
"save file\n \n Arguments:\n file_dir {str:direction} -- 文件的地址\n \n Keyword Arguments:\n client {Mongodb:Connection} -- Mongo Connection (default: {DATABASE})\n "
] |
Please provide a description of the function:def exclude_from_stock_ip_list(exclude_ip_list):
for exc in exclude_ip_list:
if exc in stock_ip_list:
stock_ip_list.remove(exc)
# 扩展市场
for exc in exclude_ip_list:
if exc in future_ip_list:
future_ip_list.remove(exc)
|
[
" 从stock_ip_list删除列表exclude_ip_list中的ip\n 从stock_ip_list删除列表future_ip_list中的ip\n\n :param exclude_ip_list: 需要删除的ip_list\n :return: None\n "
] |
Please provide a description of the function:def get_config(
self,
section='MONGODB',
option='uri',
default_value=DEFAULT_DB_URI
):
res = self.client.quantaxis.usersetting.find_one({'section': section})
if res:
return res.get(option, default_value)
else:
self.set_config(section, option, default_value)
return default_value
|
[
"[summary]\n\n Keyword Arguments:\n section {str} -- [description] (default: {'MONGODB'})\n option {str} -- [description] (default: {'uri'})\n default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def set_config(
self,
section='MONGODB',
option='uri',
default_value=DEFAULT_DB_URI
):
t = {'section': section, option: default_value}
self.client.quantaxis.usersetting.update(
{'section': section}, {'$set':t}, upsert=True)
|
[
"[summary]\n\n Keyword Arguments:\n section {str} -- [description] (default: {'MONGODB'})\n option {str} -- [description] (default: {'uri'})\n default_value {[type]} -- [description] (default: {DEFAULT_DB_URI})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def get_or_set_section(
self,
config,
section,
option,
DEFAULT_VALUE,
method='get'
):
try:
if isinstance(DEFAULT_VALUE, str):
val = DEFAULT_VALUE
else:
val = json.dumps(DEFAULT_VALUE)
if method == 'get':
return self.get_config(section, option)
else:
self.set_config(section, option, val)
return val
except:
self.set_config(section, option, val)
return val
|
[
"[summary]\n\n Arguments:\n config {[type]} -- [description]\n section {[type]} -- [description]\n option {[type]} -- [description]\n DEFAULT_VALUE {[type]} -- [description]\n\n Keyword Arguments:\n method {str} -- [description] (default: {'get'})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_util_date_str2int(date):
# return int(str(date)[0:4] + str(date)[5:7] + str(date)[8:10])
if isinstance(date, str):
return int(str().join(date.split('-')))
elif isinstance(date, int):
return date
|
[
"\n 日期字符串 '2011-09-11' 变换成 整数 20110911\n 日期字符串 '2018-12-01' 变换成 整数 20181201\n :param date: str日期字符串\n :return: 类型int\n "
] |
Please provide a description of the function:def QA_util_date_int2str(int_date):
date = str(int_date)
if len(date) == 8:
return str(date[0:4] + '-' + date[4:6] + '-' + date[6:8])
elif len(date) == 10:
return date
|
[
"\n 类型datetime.datatime\n :param date: int 8位整数\n :return: 类型str\n "
] |
Please provide a description of the function:def QA_util_to_datetime(time):
if len(str(time)) == 10:
_time = '{} 00:00:00'.format(time)
elif len(str(time)) == 19:
_time = str(time)
else:
QA_util_log_info('WRONG DATETIME FORMAT {}'.format(time))
return datetime.datetime.strptime(_time, '%Y-%m-%d %H:%M:%S')
|
[
"\n 字符串 '2018-01-01' 转变成 datatime 类型\n :param time: 字符串str -- 格式必须是 2018-01-01 ,长度10\n :return: 类型datetime.datatime\n "
] |
Please provide a description of the function:def QA_util_datetime_to_strdate(dt):
strdate = "%04d-%02d-%02d" % (dt.year, dt.month, dt.day)
return strdate
|
[
"\n :param dt: pythone datetime.datetime\n :return: 1999-02-01 string type\n "
] |
Please provide a description of the function:def QA_util_datetime_to_strdatetime(dt):
strdatetime = "%04d-%02d-%02d %02d:%02d:%02d" % (
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second
)
return strdatetime
|
[
"\n :param dt: pythone datetime.datetime\n :return: 1999-02-01 09:30:91 string type\n "
] |
Please provide a description of the function:def QA_util_date_stamp(date):
datestr = str(date)[0:10]
date = time.mktime(time.strptime(datestr, '%Y-%m-%d'))
return date
|
[
"\n 字符串 '2018-01-01' 转变成 float 类型时间 类似 time.time() 返回的类型\n :param date: 字符串str -- 格式必须是 2018-01-01 ,长度10\n :return: 类型float\n "
] |
Please provide a description of the function:def QA_util_time_stamp(time_):
if len(str(time_)) == 10:
# yyyy-mm-dd格式
return time.mktime(time.strptime(time_, '%Y-%m-%d'))
elif len(str(time_)) == 16:
# yyyy-mm-dd hh:mm格式
return time.mktime(time.strptime(time_, '%Y-%m-%d %H:%M'))
else:
timestr = str(time_)[0:19]
return time.mktime(time.strptime(timestr, '%Y-%m-%d %H:%M:%S'))
|
[
"\n 字符串 '2018-01-01 00:00:00' 转变成 float 类型时间 类似 time.time() 返回的类型\n :param time_: 字符串str -- 数据格式 最好是%Y-%m-%d %H:%M:%S 中间要有空格\n :return: 类型float\n "
] |
Please provide a description of the function:def QA_util_stamp2datetime(timestamp):
try:
return datetime.datetime.fromtimestamp(timestamp)
except Exception as e:
# it won't work ??
try:
return datetime.datetime.fromtimestamp(timestamp / 1000)
except:
try:
return datetime.datetime.fromtimestamp(timestamp / 1000000)
except:
return datetime.datetime.fromtimestamp(timestamp / 1000000000)
|
[
"\n datestamp转datetime\n pandas转出来的timestamp是13位整数 要/1000\n It’s common for this to be restricted to years from 1970 through 2038.\n 从1970年开始的纳秒到当前的计数 转变成 float 类型时间 类似 time.time() 返回的类型\n :param timestamp: long类型\n :return: 类型float\n "
] |
Please provide a description of the function:def QA_util_realtime(strtime, client):
time_stamp = QA_util_date_stamp(strtime)
coll = client.quantaxis.trade_date
temp_str = coll.find_one({'date_stamp': {"$gte": time_stamp}})
time_real = temp_str['date']
time_id = temp_str['num']
return {'time_real': time_real, 'id': time_id}
|
[
"\n 查询数据库中的数据\n :param strtime: strtime str字符串 -- 1999-12-11 这种格式\n :param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取\n :return: Dictionary -- {'time_real': 时间,'id': id}\n "
] |
Please provide a description of the function:def QA_util_id2date(idx, client):
coll = client.quantaxis.trade_date
temp_str = coll.find_one({'num': idx})
return temp_str['date']
|
[
"\n 从数据库中查询 通达信时间\n :param idx: 字符串 -- 数据库index\n :param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取\n :return: Str -- 通达信数据库时间\n "
] |
Please provide a description of the function:def QA_util_is_trade(date, code, client):
coll = client.quantaxis.stock_day
date = str(date)[0:10]
is_trade = coll.find_one({'code': code, 'date': date})
try:
len(is_trade)
return True
except:
return False
|
[
"\n 判断是否是交易日\n 从数据库中查询\n :param date: str类型 -- 1999-12-11 这种格式 10位字符串\n :param code: str类型 -- 股票代码 例如 603658 , 6位字符串\n :param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取\n :return: Boolean -- 是否是交易时间\n "
] |
Please provide a description of the function: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_list.append('<')
if gte != None:
fun_list.append('>=')
if lte != None:
fun_list.append('<=')
assert len(fun_list) > 0
true_list = []
try:
for item in fun_list:
if item == '>':
if __realtime.strftime('%H') > gt:
true_list.append(0)
else:
true_list.append(1)
elif item == '<':
if __realtime.strftime('%H') < lt:
true_list.append(0)
else:
true_list.append(1)
elif item == '>=':
if __realtime.strftime('%H') >= gte:
true_list.append(0)
else:
true_list.append(1)
elif item == '<=':
if __realtime.strftime('%H') <= lte:
true_list.append(0)
else:
true_list.append(1)
except:
return Exception
if sum(true_list) > 0:
return False
else:
return True
|
[] |
Please provide a description of the function:def QA_util_calc_time(func, *args, **kwargs):
_time = datetime.datetime.now()
func(*args, **kwargs)
print(datetime.datetime.now() - _time)
|
[
"\n '耗时长度的装饰器'\n :param func:\n :param args:\n :param kwargs:\n :return:\n "
] |
Please provide a description of the function:def high_limit(self):
'涨停价'
return self.groupby(level=1).close.apply(lambda x: round((x.shift(1) + 0.0002)*1.1, 2)).sort_index()
|
[] |
Please provide a description of the function:def next_day_low_limit(self):
"明日跌停价"
return self.groupby(level=1).close.apply(lambda x: round((x + 0.0002)*0.9, 2)).sort_index()
|
[] |
Please provide a description of the function:def get_medium_order(self, lower=200000, higher=1000000):
return self.data.query('amount>={}'.format(lower)).query('amount<={}'.format(higher))
|
[
"return medium\n\n Keyword Arguments:\n lower {[type]} -- [description] (default: {200000})\n higher {[type]} -- [description] (default: {1000000})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def shadow_calc(data):
up_shadow = abs(data.high - (max(data.open, data.close)))
down_shadow = abs(data.low - (min(data.open, data.close)))
entity = abs(data.open - data.close)
towards = True if data.open < data.close else False
print('=' * 15)
print('up_shadow : {}'.format(up_shadow))
print('down_shadow : {}'.format(down_shadow))
print('entity: {}'.format(entity))
print('towards : {}'.format(towards))
return up_shadow, down_shadow, entity, data.date, data.code
|
[
"计算上下影线\n\n Arguments:\n data {DataStruct.slice} -- 输入的是一个行情切片\n\n Returns:\n up_shadow {float} -- 上影线\n down_shdow {float} -- 下影线\n entity {float} -- 实体部分\n date {str} -- 时间\n code {str} -- 代码\n "
] |
Please provide a description of the function:def query_data(self, code, start, end, frequence, market_type=None):
try:
return self.fetcher[(market_type, frequence)](
code, start, end, frequence=frequence)
except:
pass
|
[
"\n 标准格式是numpy\n "
] |
Please provide a description of the function:def QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):
# 导入掘金模块且进行登录
try:
from gm.api import set_token
from gm.api import history
# 请自行将掘金量化的 TOKEN 替换掉 GMTOKEN
set_token("9c5601171e97994686b47b5cbfe7b2fc8bb25b09")
except:
raise ModuleNotFoundError
# 股票代码格式化
code_list = list(
map(
lambda x: "SHSE." + x if x[0] == "6" else "SZSE." + x,
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_gm_to_qa(df, type_):
if df is None or len(df) == 0:
raise ValueError("没有掘金数据")
df = df.rename(columns={
"eob": "datetime",
"volume": "vol",
"symbol": "code"
}).drop(["bob", "frequency", "position", "pre_close"], axis=1)
df["code"] = df["code"].map(str).str.slice(5, )
df["datetime"] = pd.to_datetime(df["datetime"].map(str).str.slice(
0, 19))
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)[5:], "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"]
print(start_time)
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
["1min",
"5min",
"15min",
"30min",
"60min"
].index(type_),
str(code)[5:],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = history(
symbol=code,
start_time=start_time,
end_time=end_time,
frequency=MIN_SEC[type_],
df=True
)
__data = __transform_gm_to_qa(df, type_)
if len(__data) > 1:
# print(QA_util_to_json_from_pandas(__data)[1::])
# print(__data)
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)[5:],
start_time,
end_time,
type_,
),
ui_log=ui_log,
)
if start_time != end_time:
df = history(
symbol=code,
start_time=start_time,
end_time=end_time,
frequency=MIN_SEC[type_],
df=True
)
__data = __transform_gm_to_qa(df, type_)
if len(__data) > 1:
# print(__data)
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
# print(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)
|
[
"\n 掘金实现方式\n save current day's stock_min data\n ",
"\n 将掘金数据转换为 qa 格式\n "
] |
Please provide a description of the function:def datetime(self):
'分钟线结构返回datetime 日线结构返回date'
index = self.data.index.remove_unused_levels()
return pd.to_datetime(index.levels[0])
|
[] |
Please provide a description of the function:def price_diff(self):
'返回DataStruct.price的一阶差分'
res = self.price.groupby(level=1).apply(lambda x: x.diff(1))
res.name = 'price_diff'
return res
|
[] |
Please provide a description of the function:def pvariance(self):
'返回DataStruct.price的方差 variance'
res = self.price.groupby(level=1
).apply(lambda x: statistics.pvariance(x))
res.name = 'pvariance'
return res
|
[] |
Please provide a description of the function:def bar_pct_change(self):
'返回bar的涨跌幅'
res = (self.close - self.open) / self.open
res.name = 'bar_pct_change'
return res
|
[] |
Please provide a description of the function:def bar_amplitude(self):
"返回bar振幅"
res = (self.high - self.low) / self.low
res.name = 'bar_amplitude'
return res
|
[] |
Please provide a description of the function: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
|
[] |
Please provide a description of the function: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
|
[] |
Please provide a description of the function: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
|
[] |
Please provide a description of the function:def normalized(self):
'归一化'
res = self.groupby('code').apply(lambda x: x / x.iloc[0])
return res
|
[] |
Please provide a description of the function: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
)
|
[] |
Please provide a description of the function: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
|
[] |
Please provide a description of the function:def kline_echarts(self, code=None):
def kline_formater(param):
return param.name + ':' + vars(param)
if code is None:
path_name = '.' + os.sep + 'QA_' + self.type + \
'_codepackage_' + self.if_fq + '.html'
kline = Kline(
'CodePackage_' + self.if_fq + '_' + self.type,
width=1360,
height=700,
page_title='QUANTAXIS'
)
bar = Bar()
data_splits = self.splits()
for ds in data_splits:
data = []
axis = []
if ds.type[-3:] == 'day':
datetime = np.array(ds.date.map(str))
else:
datetime = np.array(ds.datetime.map(str))
ohlc = np.array(
ds.data.loc[:,
['open',
'close',
'low',
'high']]
)
kline.add(
ds.code[0],
datetime,
ohlc,
mark_point=["max",
"min"],
is_datazoom_show=True,
datazoom_orient='horizontal'
)
return kline
else:
data = []
axis = []
ds = self.select_code(code)
data = []
#axis = []
if self.type[-3:] == 'day':
datetime = np.array(ds.date.map(str))
else:
datetime = np.array(ds.datetime.map(str))
ohlc = np.array(ds.data.loc[:, ['open', 'close', 'low', 'high']])
vol = np.array(ds.volume)
kline = Kline(
'{}__{}__{}'.format(code,
self.if_fq,
self.type),
width=1360,
height=700,
page_title='QUANTAXIS'
)
bar = Bar()
kline.add(self.code, datetime, ohlc,
mark_point=["max", "min"],
# is_label_show=True,
is_datazoom_show=True,
is_xaxis_show=False,
# is_toolbox_show=True,
tooltip_formatter='{b}:{c}', # kline_formater,
# is_more_utils=True,
datazoom_orient='horizontal')
bar.add(
self.code,
datetime,
vol,
is_datazoom_show=True,
datazoom_xaxis_index=[0,
1]
)
grid = Grid(width=1360, height=700, page_title='QUANTAXIS')
grid.add(bar, grid_top="80%")
grid.add(kline, grid_bottom="30%")
return grid
|
[
"plot the market_data"
] |
Please provide a description of the function:def query(self, context):
try:
return self.data.query(context)
except pd.core.computation.ops.UndefinedVariableError:
print('QA CANNOT QUERY THIS {}'.format(context))
pass
|
[
"\n 查询data\n "
] |
Please provide a description of the function:def groupby(
self,
by=None,
axis=0,
level=None,
as_index=True,
sort=False,
group_keys=False,
squeeze=False,
**kwargs
):
if by == self.index.names[1]:
by = None
level = 1
elif by == self.index.names[0]:
by = None
level = 0
return self.data.groupby(
by=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze
)
|
[
"仿dataframe的groupby写法,但控制了by的code和datetime\n\n Keyword Arguments:\n by {[type]} -- [description] (default: {None})\n axis {int} -- [description] (default: {0})\n level {[type]} -- [description] (default: {None})\n as_index {bool} -- [description] (default: {True})\n sort {bool} -- [description] (default: {True})\n group_keys {bool} -- [description] (default: {True})\n squeeze {bool} -- [description] (default: {False})\n observed {bool} -- [description] (default: {False})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def new(self, data=None, dtype=None, if_fq=None):
data = self.data if data is None else data
dtype = self.type if dtype is None else dtype
if_fq = self.if_fq if if_fq is None else if_fq
temp = copy(self)
temp.__init__(data, dtype, if_fq)
return temp
|
[
"\n 创建一个新的DataStruct\n data 默认是self.data\n 🛠todo 没有这个?? inplace 是否是对于原类的修改 ??\n "
] |
Please provide a description of the function:def reindex(self, ind):
if isinstance(ind, pd.MultiIndex):
try:
return self.new(self.data.reindex(ind))
except:
raise RuntimeError('QADATASTRUCT ERROR: CANNOT REINDEX')
else:
raise RuntimeError(
'QADATASTRUCT ERROR: ONLY ACCEPT MULTI-INDEX FORMAT'
)
|
[
"reindex\n\n Arguments:\n ind {[type]} -- [description]\n\n Raises:\n RuntimeError -- [description]\n RuntimeError -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def to_json(self):
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())
|
[
"\n 转换DataStruct为json\n "
] |
Please provide a description of the function:def to_hdf(self, place, name):
'IO --> hdf5'
self.data.to_hdf(place, name)
return place, name
|
[] |
Please provide a description of the function:def is_same(self, DataStruct):
if self.type == DataStruct.type and self.if_fq == DataStruct.if_fq:
return True
else:
return False
|
[
"\n 判断是否相同\n "
] |
Please provide a description of the function:def splits(self):
return list(map(lambda x: self.select_code(x), self.code))
|
[
"\n 将一个DataStruct按code分解为N个DataStruct\n "
] |
Please provide a description of the function:def add_func(self, func, *arg, **kwargs):
return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs)
|
[
"QADATASTRUCT的指标/函数apply入口\n\n Arguments:\n func {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def get_data(self, columns, type='ndarray', with_index=False):
res = self.select_columns(columns)
if type == 'ndarray':
if with_index:
return res.reset_index().values
else:
return res.values
elif type == 'list':
if with_index:
return res.reset_index().values.tolist()
else:
return res.values.tolist()
elif type == 'dataframe':
if with_index:
return res.reset_index()
else:
return res
|
[
"获取不同格式的数据\n\n Arguments:\n columns {[type]} -- [description]\n\n Keyword Arguments:\n type {str} -- [description] (default: {'ndarray'})\n with_index {bool} -- [description] (default: {False})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def pivot(self, column_):
if isinstance(column_, str):
try:
return self.data.reset_index().pivot(
index='datetime',
columns='code',
values=column_
)
except:
return self.data.reset_index().pivot(
index='date',
columns='code',
values=column_
)
elif isinstance(column_, list):
try:
return self.data.reset_index().pivot_table(
index='datetime',
columns='code',
values=column_
)
except:
return self.data.reset_index().pivot_table(
index='date',
columns='code',
values=column_
)
|
[
"增加对于多列的支持"
] |
Please provide a description of the function:def selects(self, code, start, end=None):
def _selects(code, start, end):
if end is not None:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), code), :]
else:
return self.data.loc[(slice(pd.Timestamp(start), None), code), :]
try:
return self.new(_selects(code, start, end), self.type, self.if_fq)
except:
raise ValueError(
'QA CANNOT GET THIS CODE {}/START {}/END{} '.format(
code,
start,
end
)
)
|
[
"\n 选择code,start,end\n\n 如果end不填写,默认获取到结尾\n\n @2018/06/03 pandas 的索引问题导致\n https://github.com/pandas-dev/pandas/issues/21299\n\n 因此先用set_index去重做一次index\n 影响的有selects,select_time,select_month,get_bar\n\n @2018/06/04\n 当选择的时间越界/股票不存在,raise ValueError\n\n @2018/06/04 pandas索引问题已经解决\n 全部恢复\n "
] |
Please provide a description of the function:def select_time(self, start, end=None):
def _select_time(start, end):
if end is not None:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(None)), :]
else:
return self.data.loc[(slice(pd.Timestamp(start), None), slice(None)), :]
try:
return self.new(_select_time(start, end), self.type, self.if_fq)
except:
raise ValueError(
'QA CANNOT GET THIS START {}/END{} '.format(start,
end)
)
|
[
"\n 选择起始时间\n 如果end不填写,默认获取到结尾\n\n @2018/06/03 pandas 的索引问题导致\n https://github.com/pandas-dev/pandas/issues/21299\n\n 因此先用set_index去重做一次index\n 影响的有selects,select_time,select_month,get_bar\n\n @2018/06/04\n 当选择的时间越界/股票不存在,raise ValueError\n\n @2018/06/04 pandas索引问题已经解决\n 全部恢复\n "
] |
Please provide a description of the function:def select_day(self, day):
def _select_day(day):
return self.data.loc[day, slice(None)]
try:
return self.new(_select_day(day), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT GET THIS Day {} '.format(day))
|
[
"选取日期(一般用于分钟线)\n\n Arguments:\n day {[type]} -- [description]\n\n Raises:\n ValueError -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def select_month(self, month):
def _select_month(month):
return self.data.loc[month, slice(None)]
try:
return self.new(_select_month(month), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT GET THIS Month {} '.format(month))
|
[
"\n 选择月份\n\n @2018/06/03 pandas 的索引问题导致\n https://github.com/pandas-dev/pandas/issues/21299\n\n 因此先用set_index去重做一次index\n 影响的有selects,select_time,select_month,get_bar\n\n @2018/06/04\n 当选择的时间越界/股票不存在,raise ValueError\n\n @2018/06/04 pandas索引问题已经解决\n 全部恢复\n "
] |
Please provide a description of the function:def select_code(self, code):
def _select_code(code):
return self.data.loc[(slice(None), code), :]
try:
return self.new(_select_code(code), self.type, self.if_fq)
except:
raise ValueError('QA CANNOT FIND THIS CODE {}'.format(code))
|
[
"\n 选择股票\n\n @2018/06/03 pandas 的索引问题导致\n https://github.com/pandas-dev/pandas/issues/21299\n\n 因此先用set_index去重做一次index\n 影响的有selects,select_time,select_month,get_bar\n\n @2018/06/04\n 当选择的时间越界/股票不存在,raise ValueError\n\n @2018/06/04 pandas索引问题已经解决\n 全部恢复\n "
] |
Please provide a description of the function:def get_bar(self, code, time):
try:
return self.data.loc[(pd.Timestamp(time), code)]
except:
raise ValueError(
'DATASTRUCT CURRENTLY CANNOT FIND THIS BAR WITH {} {}'.format(
code,
time
)
)
|
[
"\n 获取一个bar的数据\n 返回一个series\n 如果不存在,raise ValueError\n "
] |
Please provide a description of the function:def QA_SU_trans_stock_min(client=DATABASE, ui_log=None, ui_progress=None,
data_path: str = "D:\\skysoft\\", type_="1min"):
code_list = list(map(lambda x: x[2:8], os.listdir(data_path)))
coll = client.stock_min
coll.create_index([
("code", pymongo.ASCENDING),
("time_stamp", pymongo.ASCENDING),
("date_stamp", pymongo.ASCENDING),
])
err = []
def __transform_ss_to_qa(file_path: str = None, end_time: str = None, type_="1min"):
if file_path is None:
raise ValueError("输入文件地址")
df_local = pd.read_csv(file_path)
# 列名处理
df_local = df_local.rename(
columns={"time": "datetime", "volume": "vol"})
# 格式处理
df_local = df_local.assign(
code=df_local.symbol.map(str).str.slice(2),
date=df_local.datetime.map(str).str.slice(0, 10),
).drop(
"symbol", axis=1)
df_local = df_local.assign(
datetime=pd.to_datetime(df_local.datetime),
date_stamp=df_local.date.apply(lambda x: QA_util_date_stamp(x)),
time_stamp=df_local.datetime.apply(
lambda x: QA_util_time_stamp(x)),
type="1min",
).set_index(
"datetime", drop=False)
df_local = df_local.loc[slice(None, end_time)]
df_local["datetime"] = df_local["datetime"].map(str)
df_local["type"] = type_
return df_local[[
"open",
"close",
"high",
"low",
"vol",
"amount",
"datetime",
"code",
"date",
"date_stamp",
"time_stamp",
"type",
]]
def __saving_work(code, coll):
QA_util_log_info(
"##JOB03 Now Saving STOCK_MIN ==== {}".format(code), ui_log=ui_log)
try:
col_filter = {"code": code, "type": type_}
ref_ = coll.find(col_filter)
end_time = ref_[0]['datetime'] # 本地存储分钟数据最早的时间
filename = "SH"+code+".csv" if code[0] == '6' else "SZ"+code+".csv"
__data = __transform_ss_to_qa(
data_path+filename, end_time, type_) # 加入 end_time, 避免出现数据重复
QA_util_log_info(
"##JOB03.{} Now Saving {} from {} to {} == {}".format(
type_,
code,
__data['datetime'].iloc[0],
__data['datetime'].iloc[-1],
type_,
),
ui_log=ui_log,
)
if len(__data) > 1:
coll.insert_many(
QA_util_to_json_from_pandas(__data)[1::])
except Exception as e:
QA_util_log_info(e, ui_log=ui_log)
err.append(code)
QA_util_log_info(err, ui_log=ui_log)
executor = ThreadPoolExecutor(max_workers=4)
res = {
executor.submit(__saving_work, code_list[i_], coll)
for i_ in range(len(code_list))
}
count = 0
for i_ in concurrent.futures.as_completed(res):
strProgress = "TRANSFORM PROGRESS {} ".format(
str(float(count / len(code_list) * 100))[0:4] + "%")
intProgress = int(count / len(code_list) * 10000.0)
count = count + 1
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log)
if len(err) < 1:
QA_util_log_info("SUCCESS", ui_log=ui_log)
else:
QA_util_log_info(" ERROR CODE \n ", ui_log=ui_log)
QA_util_log_info(err, ui_log=ui_log)
|
[
"\n 将天软本地数据导入 QA 数据库\n :param client:\n :param ui_log:\n :param ui_progress:\n :param data_path: 存放天软数据的路径,默认文件名格式为类似 \"SH600000.csv\" 格式\n ",
"\n 导入相应 csv 文件,并处理格式\n 1. 这里默认为天软数据格式:\n\n time symbol open high low close volume amount\n 0 2013-08-01 09:31:00\tSH600000\t7.92\t7.92\t7.87\t7.91\t518700\t4105381\n ...\n 2. 与 QUANTAXIS.QAFetch.QATdx.QA_fetch_get_stock_min 获取数据进行匹配,具体处理详见相应源码\n\n open close high low vol amount ...\n datetime\n 2018-12-03 09:31:00 10.99 10.90 10.99 10.90 2.211700e+06 2.425626e+07 ...\n "
] |
Please provide a description of the function:def get_best_ip_by_real_data_fetch(_type='stock'):
from QUANTAXIS.QAUtil.QADate import QA_util_today_str
import time
#找到前两天的有效交易日期
pre_trade_date=QA_util_get_real_date(QA_util_today_str())
pre_trade_date=QA_util_get_real_date(pre_trade_date)
# 某个函数获取的耗时测试
def get_stock_data_by_ip(ips):
start=time.time()
try:
QA_fetch_get_stock_transaction('000001',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port'])
end=time.time()
return end-start
except:
return 9999
def get_future_data_by_ip(ips):
start=time.time()
try:
QA_fetch_get_future_transaction('RBL8',pre_trade_date,pre_trade_date,2,ips['ip'],ips['port'])
end=time.time()
return end-start
except:
return 9999
func,ip_list=0,0
if _type=='stock':
func,ip_list=get_stock_data_by_ip,stock_ip_list
else:
func,ip_list=get_future_data_by_ip,future_ip_list
from pathos.multiprocessing import Pool
def multiMap(func,sequence):
res=[]
pool=Pool(4)
for i in sequence:
res.append(pool.apply_async(func,(i,)))
pool.close()
pool.join()
return list(map(lambda x:x.get(),res))
res=multiMap(func,ip_list)
index=res.index(min(res))
return ip_list[index]
|
[
"\n 用特定的数据获取函数测试数据获得的时间,从而选择下载数据最快的服务器ip\n 默认使用特定品种1min的方式的获取\n "
] |
Please provide a description of the function:def get_ip_list_by_multi_process_ping(ip_list=[], n=0, _type='stock'):
''' 根据ping排序返回可用的ip列表
2019 03 31 取消参数filename
:param ip_list: ip列表
:param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip
:param _type: ip类型
:return: 可以ping通的ip列表
'''
cache = QA_util_cache()
results = cache.get(_type)
if results:
# read the data from cache
print('loading ip list from {} cache.'.format(_type))
else:
ips = [(x['ip'], x['port'], _type) for x in ip_list]
ps = Parallelism()
ps.add(ping, ips)
ps.run()
data = list(ps.get_results())
results = []
for i in range(len(data)):
# 删除ping不通的数据
if data[i] < datetime.timedelta(0, 9, 0):
results.append((data[i], ip_list[i]))
# 按照ping值从小大大排序
results = [x[1] for x in sorted(results, key=lambda x: x[0])]
if _type:
# store the data as binary data stream
cache.set(_type, results, age=86400)
print('saving ip list to {} cache {}.'.format(_type, len(results)))
if len(results) > 0:
if n == 0 and len(results) > 0:
return results
else:
return results[:n]
else:
print('ALL IP PING TIMEOUT!')
return [{'ip': None, 'port': None}]
|
[] |
Please provide a description of the function:def get_mainmarket_ip(ip, port):
global best_ip
if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is None:
best_ip = select_best_ip()
ip = best_ip['stock']['ip']
port = best_ip['stock']['port']
elif ip is None and port is None and best_ip['stock']['ip'] is not None and best_ip['stock']['port'] is not None:
ip = best_ip['stock']['ip']
port = best_ip['stock']['port']
else:
pass
return ip, port
|
[
"[summary]\n\n Arguments:\n ip {[type]} -- [description]\n port {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_fetch_get_security_bars(code, _type, lens, 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_security_bars(_select_type(_type), _select_market_code(
code), code, (i - 1) * 800, 800)) for i in range(1, int(lens / 800) + 2)], axis=0)
data = data \
.drop(['year', 'month', 'day', 'hour', 'minute'], axis=1, inplace=False) \
.assign(datetime=pd.to_datetime(data['datetime']),
date=data['datetime'].apply(lambda x: str(x)[0:10]),
date_stamp=data['datetime'].apply(
lambda x: QA_util_date_stamp(x)),
time_stamp=data['datetime'].apply(
lambda x: QA_util_time_stamp(x)),
type=_type, code=str(code)) \
.set_index('datetime', drop=False, inplace=False).tail(lens)
if data is not None:
return data
else:
return None
|
[
"按bar长度推算数据\n\n Arguments:\n code {[type]} -- [description]\n _type {[type]} -- [description]\n lens {[type]} -- [description]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {best_ip})\n port {[type]} -- [description] (default: {7709})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_fetch_get_stock_day(code, start_date, end_date, if_fq='00', frequence='day', ip=None, port=None):
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
try:
with api.connect(ip, port, time_out=0.7):
if frequence in ['day', 'd', 'D', 'DAY', 'Day']:
frequence = 9
elif frequence in ['w', 'W', 'Week', 'week']:
frequence = 5
elif frequence in ['month', 'M', 'm', 'Month']:
frequence = 6
elif frequence in ['quarter', 'Q', 'Quarter', 'q']:
frequence = 10
elif frequence in ['y', 'Y', 'year', 'Year']:
frequence = 11
start_date = str(start_date)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
data = pd.concat([api.to_df(api.get_security_bars(frequence, _select_market_code(
code), code, (int(lens / 800) - i) * 800, 800)) for i in range(int(lens / 800) + 1)], axis=0)
# 这里的问题是: 如果只取了一天的股票,而当天停牌, 那么就直接返回None了
if len(data) < 1:
return None
data = data[data['open'] != 0]
data = data.assign(date=data['datetime'].apply(lambda x: str(x[0:10])),
code=str(code),
date_stamp=data['datetime'].apply(lambda x: QA_util_date_stamp(str(x)[0:10]))) \
.set_index('date', drop=False, inplace=False)
end_date = str(end_date)[0:10]
data = data.drop(['year', 'month', 'day', 'hour', 'minute', 'datetime'], axis=1)[
start_date:end_date]
if if_fq in ['00', 'bfq']:
return data
else:
print('CURRENTLY NOT SUPPORT REALTIME FUQUAN')
return None
# xdxr = QA_fetch_get_stock_xdxr(code)
# if if_fq in ['01','qfq']:
# return QA_data_make_qfq(data,xdxr)
# elif if_fq in ['02','hfq']:
# return QA_data_make_hfq(data,xdxr)
except Exception as e:
if isinstance(e, TypeError):
print('Tushare内置的pytdx版本和QUANTAXIS使用的pytdx 版本不同, 请重新安装pytdx以解决此问题')
print('pip uninstall pytdx')
print('pip install pytdx')
else:
print(e)
|
[
"获取日线及以上级别的数据\n\n\n Arguments:\n code {str:6} -- code 是一个单独的code 6位长度的str\n start_date {str:10} -- 10位长度的日期 比如'2017-01-01'\n end_date {str:10} -- 10位长度的日期 比如'2018-01-01'\n\n Keyword Arguments:\n if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhfq' --定点后复权\n frequency {str} -- day/week/month/quarter/year 也可以是简写 D/W/M/Q/Y\n ip {str} -- [description] (default: None) ip可以通过select_best_ip()函数重新获取\n port {int} -- [description] (default: {None})\n\n\n Returns:\n pd.DataFrame/None -- 返回的是dataframe,如果出错比如只获取了一天,而当天停牌,返回None\n\n Exception:\n 如果出现网络问题/服务器拒绝, 会出现socket:time out 尝试再次获取/更换ip即可, 本函数不做处理\n "
] |
Please provide a description of the function:def for_sz(code):
if str(code)[0:2] in ['00', '30', '02']:
return 'stock_cn'
elif str(code)[0:2] in ['39']:
return 'index_cn'
elif str(code)[0:2] in ['15']:
return 'etf_cn'
elif str(code)[0:2] in ['10', '11', '12', '13']:
# 10xxxx 国债现货
# 11xxxx 债券
# 12xxxx 可转换债券
# 12xxxx 国债回购
return 'bond_cn'
elif str(code)[0:2] in ['20']:
return 'stockB_cn'
else:
return 'undefined'
|
[
"深市代码分类\n\n Arguments:\n code {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_fetch_get_index_list(ip=None, port=None):
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
with api.connect(ip, port):
data = pd.concat(
[pd.concat([api.to_df(api.get_security_list(j, i * 1000)).assign(sse='sz' if j == 0 else 'sh').set_index(
['code', 'sse'], drop=False) for i in range(int(api.get_security_count(j) / 1000) + 1)], axis=0) for j
in range(2)], axis=0)
# data.code = data.code.apply(int)
sz = data.query('sse=="sz"')
sh = data.query('sse=="sh"')
sz = sz.assign(sec=sz.code.apply(for_sz))
sh = sh.assign(sec=sh.code.apply(for_sh))
return pd.concat([sz, sh]).query('sec=="index_cn"').sort_index().assign(
name=data['name'].apply(lambda x: str(x)[0:6]))
|
[
"获取指数列表\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_fetch_get_stock_transaction_realtime(code, ip=None, port=None):
'实时分笔成交 包含集合竞价 buyorsell 1--sell 0--buy 2--盘前'
ip, port = get_mainmarket_ip(ip, port)
api = TdxHq_API()
try:
with api.connect(ip, port):
data = pd.DataFrame()
data = pd.concat([api.to_df(api.get_transaction_data(
_select_market_code(str(code)), code, (2 - i) * 2000, 2000)) for i in range(3)], axis=0)
if 'value' in data.columns:
data = data.drop(['value'], axis=1)
data = data.dropna()
day = datetime.date.today()
return data.assign(date=str(day)).assign(
datetime=pd.to_datetime(data['time'].apply(lambda x: str(day) + ' ' + str(x)))) \
.assign(code=str(code)).assign(order=range(len(data.index))).set_index('datetime', drop=False,
inplace=False)
except:
return None
|
[] |
Please provide a description of the function: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
|
[] |
Please provide a description of the function: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))
|
[] |
Please provide a description of the function: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 ')
|
[] |
Please provide a description of the function: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)
|
[] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==42 or market==28 or market==29 or market==30 or market==47')
|
[
"[summary]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n 42 3 商品指数 TI\n 60 3 主力期货合约 MA\n 28 3 郑州商品 QZ\n 29 3 大连商品 QD\n 30 3 上海期货(原油+贵金属) QS\n 47 3 中金所期货 CZ\n\n 50 3 渤海商品 BH\n 76 3 齐鲁商品 QL\n\n\n 46 11 上海黄金(伦敦金T+D) SG\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==12 or market==37')
|
[
"全球指数列表\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n 37 11 全球指数(静态) FW\n 12 5 国际指数 WI\n\n\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==50 or market==76 or market==46')
|
[
"[summary]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n 42 3 商品指数 TI\n 60 3 主力期货合约 MA\n 28 3 郑州商品 QZ\n 29 3 大连商品 QD\n 30 3 上海期货(原油+贵金属) QS\n 47 3 中金所期货 CZ\n\n 50 3 渤海商品 BH\n 76 3 齐鲁商品 QL\n\n\n 46 11 上海黄金(伦敦金T+D) SG\n "
] |
Please provide a description of the function: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 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]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n 14 3 伦敦金属 LM\n 15 3 伦敦石油 IP\n 16 3 纽约商品 CO\n 17 3 纽约石油 NY\n 18 3 芝加哥谷 CB\n 19 3 东京工业品 TO\n 20 3 纽约期货 NB\n 77 3 新加坡期货 SX\n 39 3 马来期货 ML\n\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==31 or market==48')
|
[
"[summary]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n# 港股 HKMARKET\n 27 5 香港指数 FH\n 31 2 香港主板 KH\n 48 2 香港创业板 KG\n 49 2 香港基金 KT\n 43 1 B股转H股 HB\n\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==27')
|
[
"[summary]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n# 港股 HKMARKET\n 27 5 香港指数 FH\n 31 2 香港主板 KH\n 48 2 香港创业板 KG\n 49 2 香港基金 KT\n 43 1 B股转H股 HB\n\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==49')
|
[
"[summary]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n # 港股 HKMARKET\n 27 5 香港指数 FH\n 31 2 香港主板 KH\n 48 2 香港创业板 KG\n 49 2 香港基金 KT\n 43 1 B股转H股 HB\n\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==74 or market==40 or market==41')
|
[
"[summary]\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n ## 美股 USA STOCK\n 74 13 美国股票 US\n 40 11 中国概念股 CH\n 41 11 美股知名公司 MG\n\n\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('market==38')
|
[
"宏观指标列表\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n 38 10 宏观指标 HG\n\n\n "
] |
Please provide a description of the function: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 extension_market_list
return extension_market_list.query('category==12 and market!=1')
|
[
"期权列表\n\n Keyword Arguments:\n ip {[type]} -- [description] (default: {None})\n port {[type]} -- [description] (default: {None})\n\n ## 期权 OPTION\n 1 12 临时期权(主要是50ETF)\n 4 12 郑州商品期权 OZ\n 5 12 大连商品期权 OD\n 6 12 上海商品期权 OS\n 7 12 中金所期权 OJ\n 8 12 上海股票期权 QQ\n 9 12 深圳股票期权 (推测)\n\n\n "
] |
Please provide a description of the function: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
|
[] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.