Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def QA_user_sign_up(name, password, client):
coll = client.user
if (coll.find({'username': name}).count() > 0):
print(name)
QA_util_log_info('user name is already exist')
return False
else:
return True
|
[
"只做check! 具体逻辑需要在自己的函数中实现\n\n 参见:QAWEBSERVER中的实现\n \n Arguments:\n name {[type]} -- [description]\n password {[type]} -- [description]\n client {[type]} -- [description]\n \n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def warp(self, order):
# 因为成交模式对时间的封装
if order.order_model == ORDER_MODEL.MARKET:
if order.frequence is FREQUENCE.DAY:
# exact_time = str(datetime.datetime.strptime(
# str(order.datetime), '%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1))
order.date = order.datetime[0:10]
order.datetime = '{} 09:30:00'.format(order.date)
elif order.frequence in [FREQUENCE.ONE_MIN,
FREQUENCE.FIVE_MIN,
FREQUENCE.FIFTEEN_MIN,
FREQUENCE.THIRTY_MIN,
FREQUENCE.SIXTY_MIN]:
exact_time = str(
datetime.datetime
.strptime(str(order.datetime),
'%Y-%m-%d %H:%M:%S') +
datetime.timedelta(minutes=1)
)
order.date = exact_time[0:10]
order.datetime = exact_time
self.market_data = self.get_market(order)
if self.market_data is None:
return order
order.price = (
float(self.market_data["high"]) +
float(self.market_data["low"])
) * 0.5
elif order.order_model == ORDER_MODEL.NEXT_OPEN:
try:
exact_time = str(
datetime.datetime
.strptime(str(order.datetime),
'%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1)
)
order.date = exact_time[0:10]
order.datetime = '{} 09:30:00'.format(order.date)
except:
order.datetime = '{} 15:00:00'.format(order.date)
self.market_data = self.get_market(order)
if self.market_data is None:
return order
order.price = float(self.market_data["close"])
elif order.order_model == ORDER_MODEL.CLOSE:
try:
order.datetime = self.market_data.datetime
except:
if len(str(order.datetime)) == 19:
pass
else:
order.datetime = '{} 15:00:00'.format(order.date)
self.market_data = self.get_market(order)
if self.market_data is None:
return order
order.price = float(self.market_data["close"])
elif order.order_model == ORDER_MODEL.STRICT:
'加入严格模式'
if order.frequence is FREQUENCE.DAY:
exact_time = str(
datetime.datetime
.strptime(order.datetime,
'%Y-%m-%d %H-%M-%S') + datetime.timedelta(day=1)
)
order.date = exact_time[0:10]
order.datetime = '{} 09:30:00'.format(order.date)
elif order.frequence in [FREQUENCE.ONE_MIN,
FREQUENCE.FIVE_MIN,
FREQUENCE.FIFTEEN_MIN,
FREQUENCE.THIRTY_MIN,
FREQUENCE.SIXTY_MIN]:
exact_time = str(
datetime.datetime
.strptime(order.datetime,
'%Y-%m-%d %H-%M-%S') +
datetime.timedelta(minute=1)
)
order.date = exact_time[0:10]
order.datetime = exact_time
self.market_data = self.get_market(order)
if self.market_data is None:
return order
if order.towards == 1:
order.price = float(self.market_data["high"])
else:
order.price = float(self.market_data["low"])
return order
|
[
"对order/market的封装\n\n [description]\n\n Arguments:\n order {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def get_filename():
return [(l[0],l[1]) for l in [line.strip().split(",") for line in requests.get(FINANCIAL_URL).text.strip().split('\n')]]
|
[
"\n get_filename\n "
] |
Please provide a description of the function:def download_financialzip():
result = get_filename()
res = []
for item, md5 in result:
if item in os.listdir(download_path) and md5==QA_util_file_md5('{}{}{}'.format(download_path,os.sep,item)):
print('FILE {} is already in {}'.format(item, download_path))
else:
print('CURRENTLY GET/UPDATE {}'.format(item[0:12]))
r = requests.get('http://down.tdx.com.cn:8001/fin/{}'.format(item))
file = '{}{}{}'.format(download_path, os.sep, item)
with open(file, "wb") as code:
code.write(r.content)
res.append(item)
return res
|
[
"\n 会创建一个download/文件夹\n "
] |
Please provide a description of the function:def get_df(self, data_file):
crawler = QAHistoryFinancialCrawler()
with open(data_file, 'rb') as df:
data = crawler.parse(download_file=df)
return crawler.to_df(data)
|
[
"\n 读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考\n\n https://github.com/rainx/pytdx/issues/133\n\n :param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat\n :return: pandas DataFrame格式的历史财务数据\n "
] |
Please provide a description of the function:def QA_fetch_get_sh_margin(date):
if date in trade_date_sse:
data= pd.read_excel(_sh_url.format(QA_util_date_str2int
(date)), 1).assign(date=date).assign(sse='sh')
data.columns=['code','name','leveraged_balance','leveraged_buyout','leveraged_payoff','margin_left','margin_sell','margin_repay','date','sse']
return data
else:
pass
|
[
"return shanghai margin data\n\n Arguments:\n date {str YYYY-MM-DD} -- date format\n\n Returns:\n pandas.DataFrame -- res for margin data\n "
] |
Please provide a description of the function:def QA_fetch_get_sz_margin(date):
if date in trade_date_sse:
return pd.read_excel(_sz_url.format(date)).assign(date=date).assign(sse='sz')
|
[
"return shenzhen margin data\n\n Arguments:\n date {str YYYY-MM-DD} -- date format\n\n Returns:\n pandas.DataFrame -- res for margin data\n "
] |
Please provide a description of the function:def upcoming_data(self, broker, data):
'''
更新市场数据
broker 为名字,
data 是市场数据
被 QABacktest 中run 方法调用 upcoming_data
'''
# main thread'
# if self.running_time is not None and self.running_time!= data.datetime[0]:
# for item in self.broker.keys():
# self._settle(item)
self.running_time = data.datetime[0]
for account in self.session.values():
account.run(QA_Event(
event_type=ENGINE_EVENT.UPCOMING_DATA,
# args 附加的参数
market_data=data,
broker_name=broker,
send_order=self.insert_order, # 🛠todo insert_order = insert_order
query_data=self.query_data_no_wait,
query_order=self.query_order,
query_assets=self.query_assets,
query_trade=self.query_trade
))
|
[] |
Please provide a description of the function:def start_order_threading(self):
self.if_start_orderthreading = True
self.order_handler.if_start_orderquery = True
self.trade_engine.create_kernel('ORDER', daemon=True)
self.trade_engine.start_kernel('ORDER')
self.sync_order_and_deal()
|
[
"开启查询子线程(实盘中用)\n "
] |
Please provide a description of the function:def login(self, broker_name, account_cookie, account=None):
res = False
if account is None:
if account_cookie not in self.session.keys():
self.session[account_cookie] = QA_Account(
account_cookie=account_cookie,
broker=broker_name
)
if self.sync_account(broker_name, account_cookie):
res = True
if self.if_start_orderthreading and res:
#
self.order_handler.subscribe(
self.session[account_cookie],
self.broker[broker_name]
)
else:
if account_cookie not in self.session.keys():
account.broker = broker_name
self.session[account_cookie] = account
if self.sync_account(broker_name, account_cookie):
res = True
if self.if_start_orderthreading and res:
#
self.order_handler.subscribe(
account,
self.broker[broker_name]
)
if res:
return res
else:
try:
self.session.pop(account_cookie)
except:
pass
return False
|
[
"login 登录到交易前置\n\n 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态\n\n Arguments:\n broker_name {[type]} -- [description]\n account_cookie {[type]} -- [description]\n\n Keyword Arguments:\n account {[type]} -- [description] (default: {None})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def sync_account(self, broker_name, account_cookie):
try:
if isinstance(self.broker[broker_name], QA_BacktestBroker):
pass
else:
self.session[account_cookie].sync_account(
self.broker[broker_name].query_positions(account_cookie)
)
return True
except Exception as e:
print(e)
return False
|
[
"同步账户信息\n\n Arguments:\n broker_id {[type]} -- [description]\n account_cookie {[type]} -- [description]\n "
] |
Please provide a description of the function:def _trade(self, event):
"内部函数"
print('==================================market enging: trade')
print(self.order_handler.order_queue.pending)
print('==================================')
self.order_handler._trade()
print('done')
|
[] |
Please provide a description of the function:def settle_order(self):
if self.if_start_orderthreading:
self.order_handler.run(
QA_Event(
event_type=BROKER_EVENT.SETTLE,
event_queue=self.trade_engine.kernels_dict['ORDER'].queue
)
)
|
[
"交易前置结算\n\n 1. 回测: 交易队列清空,待交易队列标记SETTLE\n 2. 账户每日结算\n 3. broker结算更新\n "
] |
Please provide a description of the function:def QA_util_to_json_from_pandas(data):
if 'datetime' in data.columns:
data.datetime = data.datetime.apply(str)
if 'date' in data.columns:
data.date = data.date.apply(str)
return json.loads(data.to_json(orient='records'))
|
[
"需要对于datetime 和date 进行转换, 以免直接被变成了时间戳"
] |
Please provide a description of the function:def QA_util_code_tostr(code):
if isinstance(code, int):
return "{:>06d}".format(code)
if isinstance(code, str):
# 聚宽股票代码格式 '600000.XSHG'
# 掘金股票代码格式 'SHSE.600000'
# Wind股票代码格式 '600000.SH'
# 天软股票代码格式 'SH600000'
if len(code) == 6:
return code
if len(code) == 8:
# 天软数据
return code[-6:]
if len(code) == 9:
return code[:6]
if len(code) == 11:
if code[0] in ["S"]:
return code.split(".")[1]
return code.split(".")[0]
raise ValueError("错误的股票代码格式")
if isinstance(code, list):
return QA_util_code_to_str(code[0])
|
[
"\n 将所有沪深股票从数字转化到6位的代码\n\n 因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1\n\n "
] |
Please provide a description of the function:def QA_util_code_tolist(code, auto_fill=True):
if isinstance(code, str):
if auto_fill:
return [QA_util_code_tostr(code)]
else:
return [code]
elif isinstance(code, list):
if auto_fill:
return [QA_util_code_tostr(item) for item in code]
else:
return [item for item in code]
|
[
"转换code==> list\n\n Arguments:\n code {[type]} -- [description]\n\n Keyword Arguments:\n auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True})\n\n Returns:\n [list] -- [description]\n "
] |
Please provide a description of the function:def subscribe_strategy(
self,
strategy_id: str,
last: int,
today=datetime.date.today(),
cost_coins=10
):
if self.coins > cost_coins:
order_id = str(uuid.uuid1())
self._subscribed_strategy[strategy_id] = {
'lasttime':
last,
'start':
str(today),
'strategy_id':
strategy_id,
'end':
QA_util_get_next_day(
QA_util_get_real_date(str(today),
towards=1),
last
),
'status':
'running',
'uuid':
order_id
}
self.coins -= cost_coins
self.coins_history.append(
[
cost_coins,
strategy_id,
str(today),
last,
order_id,
'subscribe'
]
)
return True, order_id
else:
# return QAERROR.
return False, 'Not Enough Coins'
|
[
"订阅一个策略\n\n 会扣减你的积分\n\n Arguments:\n strategy_id {str} -- [description]\n last {int} -- [description]\n\n Keyword Arguments:\n today {[type]} -- [description] (default: {datetime.date.today()})\n cost_coins {int} -- [description] (default: {10})\n "
] |
Please provide a description of the function:def unsubscribe_stratgy(self, strategy_id):
today = datetime.date.today()
order_id = str(uuid.uuid1())
if strategy_id in self._subscribed_strategy.keys():
self._subscribed_strategy[strategy_id]['status'] = 'canceled'
self.coins_history.append(
[0,
strategy_id,
str(today),
0,
order_id,
'unsubscribe']
)
|
[
"取消订阅某一个策略\n\n Arguments:\n strategy_id {[type]} -- [description]\n "
] |
Please provide a description of the function:def subscribing_strategy(self):
res = self.subscribed_strategy.assign(
remains=self.subscribed_strategy.end.apply(
lambda x: pd.Timestamp(x) - pd.Timestamp(datetime.date.today())
)
)
#res['left'] = res['end_time']
# res['remains']
res.assign(
status=res['remains'].apply(
lambda x: 'running'
if x > datetime.timedelta(days=0) else 'timeout'
)
)
return res.query('status=="running"')
|
[
"订阅一个策略\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def new_portfolio(self, portfolio_cookie=None):
'''
根据 self.user_cookie 创建一个 portfolio
:return:
如果存在 返回 新建的 QA_Portfolio
如果已经存在 返回 这个portfolio
'''
_portfolio = QA_Portfolio(
user_cookie=self.user_cookie,
portfolio_cookie=portfolio_cookie
)
if _portfolio.portfolio_cookie not in self.portfolio_list.keys():
self.portfolio_list[_portfolio.portfolio_cookie] = _portfolio
return _portfolio
else:
print(
" prortfolio with user_cookie ",
self.user_cookie,
" already exist!!"
)
return self.portfolio_list[portfolio_cookie]
|
[] |
Please provide a description of the function:def get_account(self, portfolio_cookie: str, account_cookie: str):
try:
return self.portfolio_list[portfolio_cookie][account_cookie]
except:
return None
|
[
"直接从二级目录拿到account\n\n Arguments:\n portfolio_cookie {str} -- [description]\n account_cookie {str} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def generate_simpleaccount(self):
if len(self.portfolio_list.keys()) < 1:
po = self.new_portfolio()
else:
po = list(self.portfolio_list.values())[0]
ac = po.new_account()
return ac, po
|
[
"make a simple account with a easier way\n 如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account\n 如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account\n "
] |
Please provide a description of the function:def register_account(self, account, portfolio_cookie=None):
'''
注册一个account到portfolio组合中
account 也可以是一个策略类,实现其 on_bar 方法
:param account: 被注册的account
:return:
'''
# 查找 portfolio
if len(self.portfolio_list.keys()) < 1:
po = self.new_portfolio()
elif portfolio_cookie is not None:
po = self.portfolio_list[portfolio_cookie]
else:
po = list(self.portfolio_list.values())[0]
# 把account 添加到 portfolio中去
po.add_account(account)
return (po, account)
|
[] |
Please provide a description of the function:def save(self):
if self.wechat_id is not None:
self.client.update(
{'wechat_id': self.wechat_id},
{'$set': self.message},
upsert=True
)
else:
self.client.update(
{
'username': self.username,
'password': self.password
},
{'$set': self.message},
upsert=True
)
# user ==> portfolio 的存储
# account的存储在 portfolio.save ==> account.save 中
for portfolio in list(self.portfolio_list.values()):
portfolio.save()
|
[
"\n 将QA_USER的信息存入数据库\n\n ATTENTION:\n\n 在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save\n\n "
] |
Please provide a description of the function:def sync(self):
if self.wechat_id is not None:
res = self.client.find_one({'wechat_id': self.wechat_id})
else:
res = self.client.find_one(
{
'username': self.username,
'password': self.password
}
)
if res is None:
if self.client.find_one({'username': self.username}) is None:
self.client.insert_one(self.message)
return self
else:
raise RuntimeError('账户名已存在且账户密码不匹配')
else:
self.reload(res)
return self
|
[
"基于账户/密码去sync数据库\n "
] |
Please provide a description of the function:def reload(self, message):
self.phone = message.get('phone')
self.level = message.get('level')
self.utype = message.get('utype')
self.coins = message.get('coins')
self.wechat_id = message.get('wechat_id')
self.coins_history = message.get('coins_history')
self.money = message.get('money')
self._subscribed_strategy = message.get('subuscribed_strategy')
self._subscribed_code = message.get('subscribed_code')
self.username = message.get('username')
self.password = message.get('password')
self.user_cookie = message.get('user_cookie')
#
portfolio_list = [item['portfolio_cookie'] for item in DATABASE.portfolio.find(
{'user_cookie': self.user_cookie}, {'portfolio_cookie': 1, '_id': 0})]
# portfolio_list = message.get('portfolio_list')
if len(portfolio_list) > 0:
self.portfolio_list = dict(
zip(
portfolio_list,
[
QA_Portfolio(
user_cookie=self.user_cookie,
portfolio_cookie=item
) for item in portfolio_list
]
)
)
else:
self.portfolio_list = {}
|
[
"恢复方法\n\n Arguments:\n message {[type]} -- [description]\n "
] |
Please provide a description of the function:def QA_util_format_date2str(cursor_date):
if isinstance(cursor_date, datetime.datetime):
cursor_date = str(cursor_date)[:10]
elif isinstance(cursor_date, str):
try:
cursor_date = str(pd.Timestamp(cursor_date))[:10]
except:
raise ValueError('请输入正确的日期格式, 建议 "%Y-%m-%d"')
elif isinstance(cursor_date, int):
cursor_date = str(pd.Timestamp("{:<014d}".format(cursor_date)))[:10]
else:
raise ValueError('请输入正确的日期格式,建议 "%Y-%m-%d"')
return cursor_date
|
[
"\n 对输入日期进行格式化处理,返回格式为 \"%Y-%m-%d\" 格式字符串\n 支持格式包括:\n 1. str: \"%Y%m%d\" \"%Y%m%d%H%M%S\", \"%Y%m%d %H:%M:%S\",\n \"%Y-%m-%d\", \"%Y-%m-%d %H:%M:%S\", \"%Y-%m-%d %H%M%S\"\n 2. datetime.datetime\n 3. pd.Timestamp\n 4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> \"2019-03-02\"\n\n :param cursor_date: str/datetime.datetime/int 日期或时间\n :return: str 返回字符串格式日期\n "
] |
Please provide a description of the function:def QA_util_get_next_trade_date(cursor_date, n=1):
cursor_date = QA_util_format_date2str(cursor_date)
if cursor_date in trade_date_sse:
# 如果指定日期为交易日
return QA_util_date_gap(cursor_date, n, "gt")
real_pre_trade_date = QA_util_get_real_date(cursor_date)
return QA_util_date_gap(real_pre_trade_date, n, "gt")
|
[
"\n 得到下 n 个交易日 (不包含当前交易日)\n :param date:\n :param n:\n "
] |
Please provide a description of the function:def QA_util_get_pre_trade_date(cursor_date, n=1):
cursor_date = QA_util_format_date2str(cursor_date)
if cursor_date in trade_date_sse:
return QA_util_date_gap(cursor_date, n, "lt")
real_aft_trade_date = QA_util_get_real_date(cursor_date)
return QA_util_date_gap(real_aft_trade_date, n, "lt")
|
[
"\n 得到前 n 个交易日 (不包含当前交易日)\n :param date:\n :param n:\n "
] |
Please provide a description of the function:def QA_util_if_tradetime(
_time=datetime.datetime.now(),
market=MARKET_TYPE.STOCK_CN,
code=None
):
'时间是否交易'
_time = datetime.datetime.strptime(str(_time)[0:19], '%Y-%m-%d %H:%M:%S')
if market is MARKET_TYPE.STOCK_CN:
if QA_util_if_trade(str(_time.date())[0:10]):
if _time.hour in [10, 13, 14]:
return True
elif _time.hour in [
9
] and _time.minute >= 15: # 修改成9:15 加入 9:15-9:30的盘前竞价时间
return True
elif _time.hour in [11] and _time.minute <= 30:
return True
else:
return False
else:
return False
elif market is MARKET_TYPE.FUTURE_CN:
date_today=str(_time.date())
date_yesterday=str((_time-datetime.timedelta(days=1)).date())
is_today_open=QA_util_if_trade(date_today)
is_yesterday_open=QA_util_if_trade(date_yesterday)
#考虑周六日的期货夜盘情况
if is_today_open==False: #可能是周六或者周日
if is_yesterday_open==False or (_time.hour > 2 or _time.hour == 2 and _time.minute > 30):
return False
shortName = "" # i , p
for i in range(len(code)):
ch = code[i]
if ch.isdigit(): # ch >= 48 and ch <= 57:
break
shortName += code[i].upper()
period = [
[9, 0, 10, 15],
[10, 30, 11, 30],
[13, 30, 15, 0]
]
if (shortName in ["IH", 'IF', 'IC']):
period = [
[9, 30, 11, 30],
[13, 0, 15, 0]
]
elif (shortName in ["T", "TF"]):
period = [
[9, 15, 11, 30],
[13, 0, 15, 15]
]
if 0<=_time.weekday<=4:
for i in range(len(period)):
p = period[i]
if ((_time.hour > p[0] or (_time.hour == p[0] and _time.minute >= p[1])) and (_time.hour < p[2] or (_time.hour == p[2] and _time.minute < p[3]))):
return True
#最新夜盘时间表_2019.03.29
nperiod = [
[
['AU', 'AG', 'SC'],
[21, 0, 2, 30]
],
[
['CU', 'AL', 'ZN', 'PB', 'SN', 'NI'],
[21, 0, 1, 0]
],
[
['RU', 'RB', 'HC', 'BU','FU','SP'],
[21, 0, 23, 0]
],
[
['A', 'B', 'Y', 'M', 'JM', 'J', 'P', 'I', 'L', 'V', 'PP', 'EG', 'C', 'CS'],
[21, 0, 23, 0]
],
[
['SR', 'CF', 'RM', 'MA', 'TA', 'ZC', 'FG', 'IO', 'CY'],
[21, 0, 23, 30]
],
]
for i in range(len(nperiod)):
for j in range(len(nperiod[i][0])):
if nperiod[i][0][j] == shortName:
p = nperiod[i][1]
condA = _time.hour > p[0] or (_time.hour == p[0] and _time.minute >= p[1])
condB = _time.hour < p[2] or (_time.hour == p[2] and _time.minute < p[3])
# in one day
if p[2] >= p[0]:
if ((_time.weekday >= 0 and _time.weekday <= 4) and condA and condB):
return True
else:
if (((_time.weekday >= 0 and _time.weekday <= 4) and condA) or ((_time.weekday >= 1 and _time.weekday <= 5) and condB)):
return True
return False
return False
|
[] |
Please provide a description of the function:def QA_util_get_real_date(date, trade_list=trade_date_sse, towards=-1):
date = str(date)[0:10]
if towards == 1:
while date not in trade_list:
date = str(
datetime.datetime.strptime(str(date)[0:10],
'%Y-%m-%d') +
datetime.timedelta(days=1)
)[0:10]
else:
return str(date)[0:10]
elif towards == -1:
while date not in trade_list:
date = str(
datetime.datetime.strptime(str(date)[0:10],
'%Y-%m-%d') -
datetime.timedelta(days=1)
)[0:10]
else:
return str(date)[0:10]
|
[
"\n 获取真实的交易日期,其中,第三个参数towards是表示向前/向后推\n towards=1 日期向后迭代\n towards=-1 日期向前迭代\n @ yutiansut\n\n "
] |
Please provide a description of the function:def QA_util_get_real_datelist(start, end):
real_start = QA_util_get_real_date(start, trade_date_sse, 1)
real_end = QA_util_get_real_date(end, trade_date_sse, -1)
if trade_date_sse.index(real_start) > trade_date_sse.index(real_end):
return None, None
else:
return (real_start, real_end)
|
[
"\n 取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist\n @yutiansut\n 2017/8/10\n\n 当start end中间没有交易日 返回None, None\n @yutiansut/ 2017-12-19\n "
] |
Please provide a description of the function:def QA_util_get_trade_range(start, end):
'给出交易具体时间'
start, end = QA_util_get_real_datelist(start, end)
if start is not None:
return trade_date_sse[trade_date_sse
.index(start):trade_date_sse.index(end) + 1:1]
else:
return None
|
[] |
Please provide a description of the function:def QA_util_get_trade_gap(start, end):
'返回start_day到end_day中间有多少个交易天 算首尾'
start, end = QA_util_get_real_datelist(start, end)
if start is not None:
return trade_date_sse.index(end) + 1 - trade_date_sse.index(start)
else:
return 0
|
[] |
Please provide a description of the function:def QA_util_date_gap(date, gap, methods):
'''
:param date: 字符串起始日 类型 str eg: 2018-11-11
:param gap: 整数 间隔多数个交易日
:param methods: gt大于 ,gte 大于等于, 小于lt ,小于等于lte , 等于===
:return: 字符串 eg:2000-01-01
'''
try:
if methods in ['>', 'gt']:
return trade_date_sse[trade_date_sse.index(date) + gap]
elif methods in ['>=', 'gte']:
return trade_date_sse[trade_date_sse.index(date) + gap - 1]
elif methods in ['<', 'lt']:
return trade_date_sse[trade_date_sse.index(date) - gap]
elif methods in ['<=', 'lte']:
return trade_date_sse[trade_date_sse.index(date) - gap + 1]
elif methods in ['==', '=', 'eq']:
return date
except:
return 'wrong date'
|
[] |
Please provide a description of the function:def QA_util_get_trade_datetime(dt=datetime.datetime.now()):
#dt= datetime.datetime.now()
if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0):
return str(dt.date())
else:
return QA_util_get_real_date(str(dt.date()), trade_date_sse, 1)
|
[
"交易的真实日期\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_util_get_order_datetime(dt):
#dt= datetime.datetime.now()
dt = datetime.datetime.strptime(str(dt)[0:19], '%Y-%m-%d %H:%M:%S')
if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0):
return str(dt)
else:
# print('before')
# print(QA_util_date_gap(str(dt.date()),1,'lt'))
return '{} {}'.format(
QA_util_date_gap(str(dt.date()),
1,
'lt'),
dt.time()
)
|
[
"委托的真实日期\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_util_future_to_tradedatetime(real_datetime):
if len(str(real_datetime)) >= 19:
dt = datetime.datetime.strptime(
str(real_datetime)[0:19],
'%Y-%m-%d %H:%M:%S'
)
return dt if dt.time(
) < datetime.time(21,
0) else QA_util_get_next_datetime(dt,
1)
elif len(str(real_datetime)) == 16:
dt = datetime.datetime.strptime(
str(real_datetime)[0:16],
'%Y-%m-%d %H:%M'
)
return dt if dt.time(
) < datetime.time(21,
0) else QA_util_get_next_datetime(dt,
1)
|
[
"输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换\n\n Arguments:\n real_datetime {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_util_future_to_realdatetime(trade_datetime):
if len(str(trade_datetime)) == 19:
dt = datetime.datetime.strptime(
str(trade_datetime)[0:19],
'%Y-%m-%d %H:%M:%S'
)
return dt if dt.time(
) < datetime.time(21,
0) else QA_util_get_last_datetime(dt,
1)
elif len(str(trade_datetime)) == 16:
dt = datetime.datetime.strptime(
str(trade_datetime)[0:16],
'%Y-%m-%d %H:%M'
)
return dt if dt.time(
) < datetime.time(21,
0) else QA_util_get_last_datetime(dt,
1)
|
[
"输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换\n\n Arguments:\n trade_datetime {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_util_make_hour_index(day, type_='1h'):
if QA_util_if_trade(day) is True:
return pd.date_range(
str(day) + ' 09:30:00',
str(day) + ' 11:30:00',
freq=type_,
closed='right'
).append(
pd.date_range(
str(day) + ' 13:00:00',
str(day) + ' 15:00:00',
freq=type_,
closed='right'
)
)
else:
return pd.DataFrame(['No trade'])
|
[
"创建股票的小时线的index\n\n Arguments:\n day {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_util_time_gap(time, gap, methods, type_):
'分钟线回测的时候的gap'
min_len = int(240 / int(str(type_).split('min')[0]))
day_gap = math.ceil(gap / min_len)
if methods in ['>', 'gt']:
data = pd.concat(
[
pd.DataFrame(QA_util_make_min_index(day,
type_))
for day in trade_date_sse[trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
):trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
) + day_gap + 1]
]
).reset_index()
return np.asarray(
data[data[0] > time].head(gap)[0].apply(lambda x: str(x))
).tolist()[-1]
elif methods in ['>=', 'gte']:
data = pd.concat(
[
pd.DataFrame(QA_util_make_min_index(day,
type_))
for day in trade_date_sse[trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
):trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
) + day_gap + 1]
]
).reset_index()
return np.asarray(
data[data[0] >= time].head(gap)[0].apply(lambda x: str(x))
).tolist()[-1]
elif methods in ['<', 'lt']:
data = pd.concat(
[
pd.DataFrame(QA_util_make_min_index(day,
type_))
for day in trade_date_sse[trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
) - day_gap:trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
) + 1]
]
).reset_index()
return np.asarray(
data[data[0] < time].tail(gap)[0].apply(lambda x: str(x))
).tolist()[0]
elif methods in ['<=', 'lte']:
data = pd.concat(
[
pd.DataFrame(QA_util_make_min_index(day,
type_))
for day in trade_date_sse[trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
) - day_gap:trade_date_sse.index(
str(
datetime.datetime.strptime(time,
'%Y-%m-%d %H:%M:%S').date()
)
) + 1]
]
).reset_index()
return np.asarray(
data[data[0] <= time].tail(gap)[0].apply(lambda x: str(x))
).tolist()[0]
elif methods in ['==', '=', 'eq']:
return time
|
[] |
Please provide a description of the function:def QA_util_save_csv(data, name, column=None, location=None):
# 重写了一下保存的模式
# 增加了对于可迭代对象的判断 2017/8/10
assert isinstance(data, list)
if location is None:
path = './' + str(name) + '.csv'
else:
path = location + str(name) + '.csv'
with open(path, 'w', newline='') as f:
csvwriter = csv.writer(f)
if column is None:
pass
else:
csvwriter.writerow(column)
for item in data:
if isinstance(item, list):
csvwriter.writerow(item)
else:
csvwriter.writerow([item])
|
[
"\n QA_util_save_csv(data,name,column,location)\n\n 将list保存成csv\n 第一个参数是list\n 第二个参数是要保存的名字\n 第三个参数是行的名称(可选)\n 第四个是保存位置(可选)\n\n @yutiansut\n "
] |
Please provide a description of the function:def query_positions(self, accounts):
try:
data = self.call("positions", {'client': accounts})
if data is not None:
cash_part = data.get('subAccounts', {}).get('人民币', False)
if cash_part:
cash_available = cash_part.get('可用金额', cash_part.get('可用'))
position_part = data.get('dataTable', False)
if position_part:
res = data.get('dataTable', False)
if res:
hold_headers = res['columns']
hold_headers = [
cn_en_compare[item] for item in hold_headers
]
hold_available = pd.DataFrame(
res['rows'],
columns=hold_headers
)
if len(hold_available) == 1 and hold_available.amount[0] in [
None,
'',
0
]:
hold_available = pd.DataFrame(
data=None,
columns=hold_headers
)
return {
'cash_available':
cash_available,
'hold_available':
hold_available.assign(
amount=hold_available.amount.apply(float)
).loc[:,
['code',
'amount']].set_index('code').amount
}
else:
print(data)
return False, 'None ACCOUNT'
except:
return False
|
[
"查询现金和持仓\n\n Arguments:\n accounts {[type]} -- [description]\n\n Returns:\n dict-- {'cash_available':xxx,'hold_available':xxx}\n "
] |
Please provide a description of the function:def query_clients(self):
try:
data = self.call("clients", {'client': 'None'})
if len(data) > 0:
return pd.DataFrame(data).drop(
['commandLine',
'processId'],
axis=1
)
else:
return pd.DataFrame(
None,
columns=[
'id',
'name',
'windowsTitle',
'accountInfo',
'status'
]
)
except Exception as e:
return False, e
|
[
"查询clients\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def query_orders(self, accounts, status='filled'):
try:
data = self.call("orders", {'client': accounts, 'status': status})
if data is not None:
orders = data.get('dataTable', False)
order_headers = orders['columns']
if ('成交状态' in order_headers
or '状态说明' in order_headers) and ('备注' in order_headers):
order_headers[order_headers.index('备注')] = '废弃'
order_headers = [cn_en_compare[item] for item in order_headers]
order_all = pd.DataFrame(
orders['rows'],
columns=order_headers
).assign(account_cookie=accounts)
order_all.towards = order_all.towards.apply(
lambda x: trade_towards_cn_en[x]
)
if 'order_time' in order_headers:
# 这是order_status
order_all['status'] = order_all.status.apply(
lambda x: order_status_cn_en[x]
)
if 'order_date' not in order_headers:
order_all.order_time = order_all.order_time.apply(
lambda x: QA_util_get_order_datetime(
dt='{} {}'.format(datetime.date.today(),
x)
)
)
else:
order_all = order_all.assign(
order_time=order_all.order_date
.apply(QA_util_date_int2str) + ' ' +
order_all.order_time
)
if 'trade_time' in order_headers:
order_all.trade_time = order_all.trade_time.apply(
lambda x: '{} {}'.format(datetime.date.today(),
x)
)
if status is 'filled':
return order_all.loc[:,
self.dealstatus_headers].set_index(
['account_cookie',
'realorder_id']
).sort_index()
else:
return order_all.loc[:,
self.orderstatus_headers].set_index(
['account_cookie',
'realorder_id']
).sort_index()
else:
print('response is None')
return False
except Exception as e:
print(e)
return False
|
[
"查询订单\n\n Arguments:\n accounts {[type]} -- [description]\n\n Keyword Arguments:\n status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def send_order(
self,
accounts,
code='000001',
price=9,
amount=100,
order_direction=ORDER_DIRECTION.BUY,
order_model=ORDER_MODEL.LIMIT
):
try:
#print(code, price, amount)
return self.call_post(
'orders',
{
'client': accounts,
"action": 'BUY' if order_direction == 1 else 'SELL',
"symbol": code,
"type": order_model,
"priceType": 0 if order_model == ORDER_MODEL.LIMIT else 4,
"price": price,
"amount": amount
}
)
except json.decoder.JSONDecodeError:
print(RuntimeError('TRADE ERROR'))
return None
|
[
"[summary]\n\n Arguments:\n accounts {[type]} -- [description]\n code {[type]} -- [description]\n price {[type]} -- [description]\n amount {[type]} -- [description]\n\n Keyword Arguments:\n order_direction {[type]} -- [description] (default: {ORDER_DIRECTION.BUY})\n order_model {[type]} -- [description] (default: {ORDER_MODEL.LIMIT})\n\n\n\n priceType 可选择: 上海交易所:\n\n 0 - 限价委托\n 4 - 五档即时成交剩余撤销\n 6 - 五档即时成交剩余转限\n\n 深圳交易所:\n\n 0 - 限价委托\n 1 - 对手方最优价格委托\n 2 - 本方最优价格委托\n 3 - 即时成交剩余撤销委托\n 4 - 五档即时成交剩余撤销\n 5 - 全额成交或撤销委托\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def get_indicator(self, time, code, indicator_name=None):
try:
return self.data.loc[(pd.Timestamp(time), code), indicator_name]
except:
raise ValueError('CANNOT FOUND THIS DATE&CODE')
|
[
"\n 获取某一时间的某一只股票的指标\n "
] |
Please provide a description of the function:def get_timerange(self, start, end, code=None):
try:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(code)), :]
except:
return ValueError('CANNOT FOUND THIS TIME RANGE')
|
[
"\n 获取某一段时间的某一只股票的指标\n "
] |
Please provide a description of the function:def QA_SU_save_stock_terminated(client=DATABASE):
'''
获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。
collection:
code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期
:param client:
:return: None
'''
# 🛠todo 已经失效从wind 资讯里获取
# 这个函数已经失效
print("!!! tushare 这个函数已经失效!!!")
df = QATs.get_terminated()
#df = QATs.get_suspended()
print(
" Get stock terminated from tushare,stock count is %d (终止上市股票列表)" %
len(df)
)
coll = client.stock_terminated
client.drop_collection(coll)
json_data = json.loads(df.reset_index().to_json(orient='records'))
coll.insert(json_data)
print(" 保存终止上市股票列表 到 stock_terminated collection, OK")
|
[] |
Please provide a description of the function:def QA_SU_save_stock_info_tushare(client=DATABASE):
'''
获取 股票的 基本信息,包含股票的如下信息
code,代码
name,名称
industry,所属行业
area,地区
pe,市盈率
outstanding,流通股本(亿)
totals,总股本(亿)
totalAssets,总资产(万)
liquidAssets,流动资产
fixedAssets,固定资产
reserved,公积金
reservedPerShare,每股公积金
esp,每股收益
bvps,每股净资
pb,市净率
timeToMarket,上市日期
undp,未分利润
perundp, 每股未分配
rev,收入同比(%)
profit,利润同比(%)
gpr,毛利率(%)
npr,净利润率(%)
holders,股东人数
add by tauruswang
在命令行工具 quantaxis 中输入 save stock_info_tushare 中的命令
:param client:
:return:
'''
df = QATs.get_stock_basics()
print(" Get stock info from tushare,stock count is %d" % len(df))
coll = client.stock_info_tushare
client.drop_collection(coll)
json_data = json.loads(df.reset_index().to_json(orient='records'))
coll.insert(json_data)
print(" Save data to stock_info_tushare collection, OK")
|
[] |
Please provide a description of the function:def QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):
'''
save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用
'''
stock_list = QA_fetch_get_stock_list()
# TODO: 重命名stock_day_ts
coll_stock_day = client.stock_day_ts
coll_stock_day.create_index(
[("code",
pymongo.ASCENDING),
("date_stamp",
pymongo.ASCENDING)]
)
err = []
num_stocks = len(stock_list)
for index, ts_code in enumerate(stock_list):
QA_util_log_info('The {} of Total {}'.format(index, num_stocks))
strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format(
str(float(index / num_stocks * 100))[0:4] + '%',
ui_log
)
intProgressToLog = int(float(index / num_stocks * 100))
QA_util_log_info(
strProgressToLog,
ui_log=ui_log,
ui_progress=ui_progress,
ui_progress_int_value=intProgressToLog
)
_saving_work(ts_code,
coll_stock_day,
ui_log=ui_log,
err=err)
# 日线行情每分钟内最多调取200次,超过5000积分无限制
time.sleep(0.005)
if len(err) < 1:
QA_util_log_info('SUCCESS save stock day ^_^', ui_log)
else:
QA_util_log_info('ERROR CODE \n ', ui_log)
QA_util_log_info(err, ui_log)
|
[] |
Please provide a description of the function:def QA_util_dict_remove_key(dicts, key):
if isinstance(key, list):
for item in key:
try:
dicts.pop(item)
except:
pass
else:
try:
dicts.pop(key)
except:
pass
return dicts
|
[
"\n 输入一个dict 返回删除后的\n "
] |
Please provide a description of the function:def QA_util_sql_async_mongo_setting(uri='mongodb://localhost:27017/quantaxis'):
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# async def client():
return AsyncIOMotorClient(uri, io_loop=loop)
|
[
"异步mongo示例\n\n Keyword Arguments:\n uri {str} -- [description] (default: {'mongodb://localhost:27017/quantaxis'})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def add_account(self, account):
'portfolio add a account/stratetgy'
if account.account_cookie not in self.account_list:
if self.cash_available > account.init_cash:
account.portfolio_cookie = self.portfolio_cookie
account.user_cookie = self.user_cookie
self.cash.append(self.cash_available - account.init_cash)
self.account_list.append(account.account_cookie)
account.save()
return account
else:
pass
|
[] |
Please provide a description of the function:def drop_account(self, account_cookie):
if account_cookie in self.account_list:
res = self.account_list.remove(account_cookie)
self.cash.append(
self.cash[-1] + self.get_account_by_cookie(res).init_cash)
return True
else:
raise RuntimeError(
'account {} is not in the portfolio'.format(account_cookie)
)
|
[
"删除一个account\n\n Arguments:\n account_cookie {[type]} -- [description]\n\n Raises:\n RuntimeError -- [description]\n "
] |
Please provide a description of the function:def new_account(
self,
account_cookie=None,
init_cash=1000000,
market_type=MARKET_TYPE.STOCK_CN,
*args,
**kwargs
):
if account_cookie is None:
# 如果组合的cash_available>创建新的account所需cash
if self.cash_available >= init_cash:
temp = QA_Account(
user_cookie=self.user_cookie,
portfolio_cookie=self.portfolio_cookie,
init_cash=init_cash,
market_type=market_type,
*args,
**kwargs
)
if temp.account_cookie not in self.account_list:
#self.accounts[temp.account_cookie] = temp
self.account_list.append(temp.account_cookie)
temp.save()
self.cash.append(self.cash_available - init_cash)
return temp
else:
return self.new_account()
else:
if self.cash_available >= init_cash:
if account_cookie not in self.account_list:
acc = QA_Account(
portfolio_cookie=self.portfolio_cookie,
user_cookie=self.user_cookie,
init_cash=init_cash,
market_type=market_type,
account_cookie=account_cookie,
*args,
**kwargs
)
acc.save()
self.account_list.append(acc.account_cookie)
self.cash.append(self.cash_available - init_cash)
return acc
else:
return self.get_account_by_cookie(account_cookie)
|
[
"创建一个新的Account\n\n Keyword Arguments:\n account_cookie {[type]} -- [description] (default: {None})\n\n Returns:\n [type] -- [description]\n ",
"创建新的account\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def get_account_by_cookie(self, cookie):
'''
'give the account_cookie and return the account/strategy back'
:param cookie:
:return: QA_Account with cookie if in dict
None not in list
'''
try:
return QA_Account(
account_cookie=cookie,
user_cookie=self.user_cookie,
portfolio_cookie=self.portfolio_cookie,
auto_reload=True
)
except:
QA_util_log_info('Can not find this account')
return None
|
[] |
Please provide a description of the function:def get_account(self, account):
'''
check the account whether in the protfolio dict or not
:param account: QA_Account
:return: QA_Account if in dict
None not in list
'''
try:
return self.get_account_by_cookie(account.account_cookie)
except:
QA_util_log_info(
'Can not find this account with cookies %s' %
account.account_cookie
)
return None
|
[] |
Please provide a description of the function:def message(self):
return {
'user_cookie': self.user_cookie,
'portfolio_cookie': self.portfolio_cookie,
'account_list': list(self.account_list),
'init_cash': self.init_cash,
'cash': self.cash,
'history': self.history
}
|
[
"portfolio 的cookie\n "
] |
Please provide a description of the function:def send_order(
self,
account_cookie: str,
code=None,
amount=None,
time=None,
towards=None,
price=None,
money=None,
order_model=None,
amount_model=None,
*args,
**kwargs
):
return self.get_account_by_cookie(account_cookie).send_order(
code=code,
amount=amount,
time=time,
towards=towards,
price=price,
money=money,
order_model=order_model,
amount_model=amount_model
)
|
[
"基于portfolio对子账户下单\n\n Arguments:\n account_cookie {str} -- [description]\n\n Keyword Arguments:\n code {[type]} -- [description] (default: {None})\n amount {[type]} -- [description] (default: {None})\n time {[type]} -- [description] (default: {None})\n towards {[type]} -- [description] (default: {None})\n price {[type]} -- [description] (default: {None})\n money {[type]} -- [description] (default: {None})\n order_model {[type]} -- [description] (default: {None})\n amount_model {[type]} -- [description] (default: {None})\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def save(self):
self.client.update(
{
'portfolio_cookie': self.portfolio_cookie,
'user_cookie': self.user_cookie
},
{'$set': self.message},
upsert=True
)
|
[
"存储过程\n "
] |
Please provide a description of the function:def market_value(self):
if self.account.daily_hold is not None:
if self.if_fq:
return (
self.market_data.to_qfq().pivot('close').fillna(
method='ffill'
) * self.account.daily_hold.apply(abs)
).fillna(method='ffill')
else:
return (
self.market_data.pivot('close').fillna(method='ffill') *
self.account.daily_hold.apply(abs)
).fillna(method='ffill')
else:
return None
|
[
"每日每个股票持仓市值表\n\n Returns:\n pd.DataFrame -- 市值表\n "
] |
Please provide a description of the function:def max_dropback(self):
return round(
float(
max(
[
(self.assets.iloc[idx] - self.assets.iloc[idx::].min())
/ self.assets.iloc[idx]
for idx in range(len(self.assets))
]
)
),
2
)
|
[
"最大回撤\n "
] |
Please provide a description of the function:def total_commission(self):
return float(
-abs(round(self.account.history_table.commission.sum(),
2))
)
|
[
"总手续费\n "
] |
Please provide a description of the function:def total_tax(self):
return float(-abs(round(self.account.history_table.tax.sum(), 2)))
|
[
"总印花税\n\n "
] |
Please provide a description of the function:def profit_construct(self):
return {
'total_buyandsell':
round(
self.profit_money - self.total_commission - self.total_tax,
2
),
'total_tax':
self.total_tax,
'total_commission':
self.total_commission,
'total_profit':
self.profit_money
}
|
[
"利润构成\n\n Returns:\n dict -- 利润构成表\n "
] |
Please provide a description of the function:def profit_money(self):
return float(round(self.assets.iloc[-1] - self.assets.iloc[0], 2))
|
[
"盈利额\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def annualize_return(self):
return round(
float(self.calc_annualize_return(self.assets,
self.time_gap)),
2
)
|
[
"年化收益\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def benchmark_data(self):
return self.fetch[self.benchmark_type](
self.benchmark_code,
self.account.start_date,
self.account.end_date
)
|
[
"\n 基准组合的行情数据(一般是组合,可以调整)\n "
] |
Please provide a description of the function:def benchmark_assets(self):
return (
self.benchmark_data.close /
float(self.benchmark_data.close.iloc[0])
* float(self.assets[0])
)
|
[
"\n 基准组合的账户资产队列\n "
] |
Please provide a description of the function:def benchmark_annualize_return(self):
return round(
float(
self.calc_annualize_return(
self.benchmark_assets,
self.time_gap
)
),
2
)
|
[
"基准组合的年化收益\n\n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def beta(self):
try:
res = round(
float(
self.calc_beta(
self.profit_pct.dropna(),
self.benchmark_profitpct.dropna()
)
),
2
)
except:
print('贝塔计算错误。。')
res = 0
return res
|
[
"\n beta比率 组合的系统性风险\n "
] |
Please provide a description of the function:def alpha(self):
return round(
float(
self.calc_alpha(
self.annualize_return,
self.benchmark_annualize_return,
self.beta,
0.05
)
),
2
)
|
[
"\n alpha比率 与市场基准收益无关的超额收益率\n "
] |
Please provide a description of the function:def sharpe(self):
return round(
float(
self.calc_sharpe(self.annualize_return,
self.volatility,
0.05)
),
2
)
|
[
"\n 夏普比率\n\n "
] |
Please provide a description of the function:def plot_assets_curve(self, length=14, height=12):
plt.style.use('ggplot')
plt.figure(figsize=(length, height))
plt.subplot(211)
plt.title('BASIC INFO', fontsize=12)
plt.axis([0, length, 0, 0.6])
plt.axis('off')
i = 0
for item in ['account_cookie', 'portfolio_cookie', 'user_cookie']:
plt.text(
i,
0.5,
'{} : {}'.format(item,
self.message[item]),
fontsize=10,
rotation=0,
wrap=True
)
i += (length / 2.8)
i = 0
for item in ['benchmark_code', 'time_gap', 'max_dropback']:
plt.text(
i,
0.4,
'{} : {}'.format(item,
self.message[item]),
fontsize=10,
ha='left',
rotation=0,
wrap=True
)
i += (length / 2.8)
i = 0
for item in ['annualize_return', 'bm_annualizereturn', 'profit']:
plt.text(
i,
0.3,
'{} : {} %'.format(item,
self.message.get(item,
0) * 100),
fontsize=10,
ha='left',
rotation=0,
wrap=True
)
i += length / 2.8
i = 0
for item in ['init_cash', 'last_assets', 'volatility']:
plt.text(
i,
0.2,
'{} : {} '.format(item,
self.message[item]),
fontsize=10,
ha='left',
rotation=0,
wrap=True
)
i += length / 2.8
i = 0
for item in ['alpha', 'beta', 'sharpe']:
plt.text(
i,
0.1,
'{} : {}'.format(item,
self.message[item]),
ha='left',
fontsize=10,
rotation=0,
wrap=True
)
i += length / 2.8
plt.subplot(212)
self.assets.plot()
self.benchmark_assets.xs(self.benchmark_code, level=1).plot()
asset_p = mpatches.Patch(
color='red',
label='{}'.format(self.account.account_cookie)
)
asset_b = mpatches.Patch(
label='benchmark {}'.format(self.benchmark_code)
)
plt.legend(handles=[asset_p, asset_b], loc=0)
plt.title('ASSET AND BENCKMARK')
return plt
|
[
"\n 资金曲线叠加图\n @Roy T.Burns 2018/05/29 修改百分比显示错误\n "
] |
Please provide a description of the function:def plot_signal(self, start=None, end=None):
start = self.account.start_date if start is None else start
end = self.account.end_date if end is None else end
_, ax = plt.subplots(figsize=(20, 18))
sns.heatmap(
self.account.trade.reset_index().drop(
'account_cookie',
axis=1
).set_index('datetime').loc[start:end],
cmap="YlGnBu",
linewidths=0.05,
ax=ax
)
ax.set_title(
'SIGNAL TABLE --ACCOUNT: {}'.format(self.account.account_cookie)
)
ax.set_xlabel('Code')
ax.set_ylabel('DATETIME')
return plt
|
[
"\n 使用热力图画出买卖信号\n "
] |
Please provide a description of the function:def pnl_lifo(self):
X = dict(
zip(
self.target.code,
[LifoQueue() for i in range(len(self.target.code))]
)
)
pair_table = []
for _, data in self.target.history_table_min.iterrows():
while True:
if X[data.code].qsize() == 0:
X[data.code].put((data.datetime, data.amount, data.price))
break
else:
l = X[data.code].get()
if (l[1] * data.amount) < 0:
# 原有多仓/ 平仓 或者原有空仓/平仓
if abs(l[1]) > abs(data.amount):
temp = (l[0], l[1] + data.amount, l[2])
X[data.code].put_nowait(temp)
if data.amount < 0:
pair_table.append(
[
data.code,
data.datetime,
l[0],
abs(data.amount),
data.price,
l[2]
]
)
break
else:
pair_table.append(
[
data.code,
l[0],
data.datetime,
abs(data.amount),
l[2],
data.price
]
)
break
elif abs(l[1]) < abs(data.amount):
data.amount = data.amount + l[1]
if data.amount < 0:
pair_table.append(
[
data.code,
data.datetime,
l[0],
l[1],
data.price,
l[2]
]
)
else:
pair_table.append(
[
data.code,
l[0],
data.datetime,
l[1],
l[2],
data.price
]
)
else:
if data.amount < 0:
pair_table.append(
[
data.code,
data.datetime,
l[0],
abs(data.amount),
data.price,
l[2]
]
)
break
else:
pair_table.append(
[
data.code,
l[0],
data.datetime,
abs(data.amount),
l[2],
data.price
]
)
break
else:
X[data.code].put_nowait(l)
X[data.code].put_nowait(
(data.datetime,
data.amount,
data.price)
)
break
pair_title = [
'code',
'sell_date',
'buy_date',
'amount',
'sell_price',
'buy_price'
]
pnl = pd.DataFrame(pair_table, columns=pair_title).set_index('code')
pnl = pnl.assign(
unit=pnl.code.apply(lambda x: self.market_preset.get_unit(x)),
pnl_ratio=(pnl.sell_price / pnl.buy_price) - 1,
sell_date=pd.to_datetime(pnl.sell_date),
buy_date=pd.to_datetime(pnl.buy_date)
)
pnl = pnl.assign(
pnl_money=(pnl.sell_price - pnl.buy_price) * pnl.amount * pnl.unit,
hold_gap=abs(pnl.sell_date - pnl.buy_date),
if_buyopen=(pnl.sell_date -
pnl.buy_date) > datetime.timedelta(days=0)
)
pnl = pnl.assign(
openprice=pnl.if_buyopen.apply(
lambda pnl: 1 if pnl else 0) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_price,
opendate=pnl.if_buyopen.apply(
lambda pnl: 1 if pnl else 0) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_date.map(str),
closeprice=pnl.if_buyopen.apply(
lambda pnl: 0 if pnl else 1) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_price,
closedate=pnl.if_buyopen.apply(
lambda pnl: 0 if pnl else 1) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_date.map(str))
return pnl.set_index('code')
|
[
"\n 使用后进先出法配对成交记录\n "
] |
Please provide a description of the function:def plot_pnlratio(self):
plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_ratio)
plt.gcf().autofmt_xdate()
return plt
|
[
"\n 画出pnl比率散点图\n "
] |
Please provide a description of the function:def plot_pnlmoney(self):
plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_money)
plt.gcf().autofmt_xdate()
return plt
|
[
"\n 画出pnl盈亏额散点图\n "
] |
Please provide a description of the function:def win_rate(self):
data = self.pnl
try:
return round(len(data.query('pnl_money>0')) / len(data), 2)
except ZeroDivisionError:
return 0
|
[
"胜率\n\n 胜率\n 盈利次数/总次数\n "
] |
Please provide a description of the function:def next_time(self, asc=False):
_time = time.localtime(time.time() + self.next())
if asc:
return time.asctime(_time)
return time.mktime(_time)
|
[
"Get the local time of the next schedule time this job will run.\n :param bool asc: Format the result with ``time.asctime()``\n :returns: The epoch time or string representation of the epoch time that\n the job should be run next\n "
] |
Please provide a description of the function:def QA_fetch_get_future_transaction_realtime(package, code):
Engine = use(package)
if package in ['tdx', 'pytdx']:
return Engine.QA_fetch_get_future_transaction_realtime(code)
else:
return 'Unsupport packages'
|
[
"\n 期货实时tick\n "
] |
Please provide a description of the function:def QA_indicator_MA(DataFrame,*args,**kwargs):
CLOSE = DataFrame['close']
return pd.DataFrame({'MA{}'.format(N): MA(CLOSE, N) for N in list(args)})
|
[
"MA\n \n Arguments:\n DataFrame {[type]} -- [description]\n \n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def QA_indicator_MACD(DataFrame, short=12, long=26, mid=9):
CLOSE = DataFrame['close']
DIF = EMA(CLOSE, short)-EMA(CLOSE, long)
DEA = EMA(DIF, mid)
MACD = (DIF-DEA)*2
return pd.DataFrame({'DIF': DIF, 'DEA': DEA, 'MACD': MACD})
|
[
"\n MACD CALC\n "
] |
Please provide a description of the function:def QA_indicator_DMI(DataFrame, M1=14, M2=6):
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
OPEN = DataFrame.open
TR = SUM(MAX(MAX(HIGH-LOW, ABS(HIGH-REF(CLOSE, 1))),
ABS(LOW-REF(CLOSE, 1))), M1)
HD = HIGH-REF(HIGH, 1)
LD = REF(LOW, 1)-LOW
DMP = SUM(IFAND(HD>0,HD>LD,HD,0), M1)
DMM = SUM(IFAND(LD>0,LD>HD,LD,0), M1)
DI1 = DMP*100/TR
DI2 = DMM*100/TR
ADX = MA(ABS(DI2-DI1)/(DI1+DI2)*100, M2)
ADXR = (ADX+REF(ADX, M2))/2
return pd.DataFrame({
'DI1': DI1, 'DI2': DI2,
'ADX': ADX, 'ADXR': ADXR
})
|
[
"\n 趋向指标 DMI\n "
] |
Please provide a description of the function:def QA_indicator_PBX(DataFrame, N1=3, N2=5, N3=8, N4=13, N5=18, N6=24):
'瀑布线'
C = DataFrame['close']
PBX1 = (EMA(C, N1) + EMA(C, 2 * N1) + EMA(C, 4 * N1)) / 3
PBX2 = (EMA(C, N2) + EMA(C, 2 * N2) + EMA(C, 4 * N2)) / 3
PBX3 = (EMA(C, N3) + EMA(C, 2 * N3) + EMA(C, 4 * N3)) / 3
PBX4 = (EMA(C, N4) + EMA(C, 2 * N4) + EMA(C, 4 * N4)) / 3
PBX5 = (EMA(C, N5) + EMA(C, 2 * N5) + EMA(C, 4 * N5)) / 3
PBX6 = (EMA(C, N6) + EMA(C, 2 * N6) + EMA(C, 4 * N6)) / 3
DICT = {'PBX1': PBX1, 'PBX2': PBX2, 'PBX3': PBX3,
'PBX4': PBX4, 'PBX5': PBX5, 'PBX6': PBX6}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_DMA(DataFrame, M1=10, M2=50, M3=10):
CLOSE = DataFrame.close
DDD = MA(CLOSE, M1) - MA(CLOSE, M2)
AMA = MA(DDD, M3)
return pd.DataFrame({
'DDD': DDD, 'AMA': AMA
})
|
[
"\n 平均线差 DMA\n "
] |
Please provide a description of the function:def QA_indicator_MTM(DataFrame, N=12, M=6):
'动量线'
C = DataFrame.close
mtm = C - REF(C, N)
MTMMA = MA(mtm, M)
DICT = {'MTM': mtm, 'MTMMA': MTMMA}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_EXPMA(DataFrame, P1=5, P2=10, P3=20, P4=60):
CLOSE = DataFrame.close
MA1 = EMA(CLOSE, P1)
MA2 = EMA(CLOSE, P2)
MA3 = EMA(CLOSE, P3)
MA4 = EMA(CLOSE, P4)
return pd.DataFrame({
'MA1': MA1, 'MA2': MA2, 'MA3': MA3, 'MA4': MA4
})
|
[
" 指数平均线 EXPMA"
] |
Please provide a description of the function:def QA_indicator_CHO(DataFrame, N1=10, N2=20, M=6):
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
VOL = DataFrame.volume
MID = SUM(VOL*(2*CLOSE-HIGH-LOW)/(HIGH+LOW), 0)
CHO = MA(MID, N1)-MA(MID, N2)
MACHO = MA(CHO, M)
return pd.DataFrame({
'CHO': CHO, 'MACHO': MACHO
})
|
[
"\n 佳庆指标 CHO\n "
] |
Please provide a description of the function:def QA_indicator_BIAS(DataFrame, N1, N2, N3):
'乖离率'
CLOSE = DataFrame['close']
BIAS1 = (CLOSE - MA(CLOSE, N1)) / MA(CLOSE, N1) * 100
BIAS2 = (CLOSE - MA(CLOSE, N2)) / MA(CLOSE, N2) * 100
BIAS3 = (CLOSE - MA(CLOSE, N3)) / MA(CLOSE, N3) * 100
DICT = {'BIAS1': BIAS1, 'BIAS2': BIAS2, 'BIAS3': BIAS3}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_ROC(DataFrame, N=12, M=6):
'变动率指标'
C = DataFrame['close']
roc = 100 * (C - REF(C, N)) / REF(C, N)
ROCMA = MA(roc, M)
DICT = {'ROC': roc, 'ROCMA': ROCMA}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_CCI(DataFrame, N=14):
typ = (DataFrame['high'] + DataFrame['low'] + DataFrame['close']) / 3
cci = ((typ - MA(typ, N)) / (0.015 * AVEDEV(typ, N)))
a = 100
b = -100
return pd.DataFrame({
'CCI': cci, 'a': a, 'b': b
})
|
[
"\n TYP:=(HIGH+LOW+CLOSE)/3;\n CCI:(TYP-MA(TYP,N))/(0.015*AVEDEV(TYP,N));\n "
] |
Please provide a description of the function:def QA_indicator_WR(DataFrame, N, N1):
'威廉指标'
HIGH = DataFrame['high']
LOW = DataFrame['low']
CLOSE = DataFrame['close']
WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N))
WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1))
DICT = {'WR1': WR1, 'WR2': WR2}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_OSC(DataFrame, N=20, M=6):
C = DataFrame['close']
OS = (C - MA(C, N)) * 100
MAOSC = EMA(OS, M)
DICT = {'OSC': OS, 'MAOSC': MAOSC}
return pd.DataFrame(DICT)
|
[
"变动速率线\n\n 震荡量指标OSC,也叫变动速率线。属于超买超卖类指标,是从移动平均线原理派生出来的一种分析指标。\n\n 它反应当日收盘价与一段时间内平均收盘价的差离值,从而测出股价的震荡幅度。\n\n 按照移动平均线原理,根据OSC的值可推断价格的趋势,如果远离平均线,就很可能向平均线回归。\n "
] |
Please provide a description of the function:def QA_indicator_RSI(DataFrame, N1=12, N2=26, N3=9):
'相对强弱指标RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;'
CLOSE = DataFrame['close']
LC = REF(CLOSE, 1)
RSI1 = SMA(MAX(CLOSE - LC, 0), N1) / SMA(ABS(CLOSE - LC), N1) * 100
RSI2 = SMA(MAX(CLOSE - LC, 0), N2) / SMA(ABS(CLOSE - LC), N2) * 100
RSI3 = SMA(MAX(CLOSE - LC, 0), N3) / SMA(ABS(CLOSE - LC), N3) * 100
DICT = {'RSI1': RSI1, 'RSI2': RSI2, 'RSI3': RSI3}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_ADTM(DataFrame, N=23, M=8):
'动态买卖气指标'
HIGH = DataFrame.high
LOW = DataFrame.low
OPEN = DataFrame.open
DTM = IF(OPEN > REF(OPEN, 1), MAX((HIGH - OPEN), (OPEN - REF(OPEN, 1))), 0)
DBM = IF(OPEN < REF(OPEN, 1), MAX((OPEN - LOW), (OPEN - REF(OPEN, 1))), 0)
STM = SUM(DTM, N)
SBM = SUM(DBM, N)
ADTM1 = IF(STM > SBM, (STM - SBM) / STM,
IF(STM != SBM, (STM - SBM) / SBM, 0))
MAADTM = MA(ADTM1, M)
DICT = {'ADTM': ADTM1, 'MAADTM': MAADTM}
return pd.DataFrame(DICT)
|
[] |
Please provide a description of the function:def QA_indicator_ASI(DataFrame, M1=26, M2=10):
CLOSE = DataFrame['close']
HIGH = DataFrame['high']
LOW = DataFrame['low']
OPEN = DataFrame['open']
LC = REF(CLOSE, 1)
AA = ABS(HIGH - LC)
BB = ABS(LOW-LC)
CC = ABS(HIGH - REF(LOW, 1))
DD = ABS(LC - REF(OPEN, 1))
R = IFAND(AA > BB, AA > CC, AA+BB/2+DD/4,
IFAND(BB > CC, BB > AA, BB+AA/2+DD/4, CC+DD/4))
X = (CLOSE - LC + (CLOSE - OPEN) / 2 + LC - REF(OPEN, 1))
SI = 16*X/R*MAX(AA, BB)
ASI = SUM(SI, M1)
ASIT = MA(ASI, M2)
return pd.DataFrame({
'ASI': ASI, 'ASIT': ASIT
})
|
[
"\n LC=REF(CLOSE,1);\n AA=ABS(HIGH-LC);\n BB=ABS(LOW-LC);\n CC=ABS(HIGH-REF(LOW,1));\n DD=ABS(LC-REF(OPEN,1));\n R=IF(AA>BB AND AA>CC,AA+BB/2+DD/4,IF(BB>CC AND BB>AA,BB+AA/2+DD/4,CC+DD/4));\n X=(CLOSE-LC+(CLOSE-OPEN)/2+LC-REF(OPEN,1));\n SI=16*X/R*MAX(AA,BB);\n ASI:SUM(SI,M1);\n ASIT:MA(ASI,M2);\n "
] |
Please provide a description of the function:def QA_indicator_OBV(DataFrame):
VOL = DataFrame.volume
CLOSE = DataFrame.close
return pd.DataFrame({
'OBV': np.cumsum(IF(CLOSE > REF(CLOSE, 1), VOL, IF(CLOSE < REF(CLOSE, 1), -VOL, 0)))/10000
})
|
[
"能量潮"
] |
Please provide a description of the function:def QA_indicator_BOLL(DataFrame, N=20, P=2):
'布林线'
C = DataFrame['close']
boll = MA(C, N)
UB = boll + P * STD(C, N)
LB = boll - P * STD(C, N)
DICT = {'BOLL': boll, 'UB': UB, 'LB': LB}
return pd.DataFrame(DICT)
|
[] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.