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 ... | [
"对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 {... | [
"\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','... | [
"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]:
... | [] |
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... | [
"开启查询子线程(实盘中用)\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=accoun... | [
"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 [... |
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.broke... | [
"同步账户信息\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 le... | [
"\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==> 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._s... | [
"订阅一个策略\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'
sel... | [
"取消订阅某一个策略\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... | [
"订阅一个策略\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,
... | [] |
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())... | [] |
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(
... | [
"\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,
'... | [
"基于账户/密码去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_h... | [
"恢复方法\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:
... | [
"\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... |
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(cu... | [
"\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 ... | [
"\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_... | [] |
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],
... | [
"\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
... | [
"\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:
... | [] |
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']:
... | [] |
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()), t... | [
"交易的真实日期\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:
# pri... | [
"委托的真实日期\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,... | [
"输入是真实交易时间,返回按期货交易所规定的时间* 适用于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(2... | [
"输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换\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... | [
"创建股票的小时线的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_ma... | [] |
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'
wi... | [
"\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:
... | [
"查询现金和持仓\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'],
... | [
"查询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 = or... | [
"查询订单\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, pr... | [
"[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: {ORDE... |
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... | [] |
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,流... | [] |
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 = Q... | [] |
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
... | [
"\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()
... | [
"异步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
ac... | [] |
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)
r... | [
"删除一个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_a... | [
"创建一个新的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... | [] |
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_accoun... | [] |
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,
... | [
"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,
... | [
"基于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 ... |
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.acco... | [
"每日每个股票持仓市值表\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 id... | [
"最大回撤\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,
... | [
"利润构成\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()
)
),
... | [
"\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
)
... | [
"\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')
... | [
"\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.... | [
"\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... | [
"\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-RE... | [
"\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) + ... | [] |
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)
... | [
"\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 = {'B... | [] |
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, ... | [] |
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... | [] |
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 - ... | [] |
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... | [
"\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:M... |
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.