Search is not available for this dataset
text stringlengths 75 104k |
|---|
def cash_table(self):
'现金的table'
_cash = pd.DataFrame(
data=[self.cash[1::],
self.time_index_max],
index=['cash',
'datetime']
).T
_cash = _cash.assign(
date=_cash.datetime.apply(lambda x: pd.to_datetime(str(x)[0:10]... |
def hold(self):
"""真实持仓
"""
return pd.concat(
[self.init_hold,
self.hold_available]
).groupby('code').sum().replace(0,
np.nan).dropna().sort_index() |
def hold_available(self):
"""可用持仓
"""
return self.history_table.groupby('code').amount.sum().replace(
0,
np.nan
).dropna().sort_index() |
def trade(self):
"""每次交易的pivot表
Returns:
pd.DataFrame
此处的pivot_table一定要用np.sum
"""
return self.history_table.pivot_table(
index=['datetime',
'account_cookie'],
columns='code',
values='amount',
a... |
def daily_cash(self):
'每日交易结算时的现金表'
res = self.cash_table.drop_duplicates(subset='date', keep='last')
le=pd.DataFrame(pd.Series(data=None, index=pd.to_datetime(self.trade_range_max).set_names('date'), name='predrop'))
ri=res.set_index('date')
res_=pd.merge(le,ri,how='left',left_i... |
def daily_hold(self):
'每日交易结算时的持仓表'
data = self.trade.cumsum()
if len(data) < 1:
return None
else:
# print(data.index.levels[0])
data = data.assign(account_cookie=self.account_cookie).assign(
date=pd.to_datetime(data.index.levels[0]).da... |
def daily_frozen(self):
'每日交易结算时的持仓表'
res_=self.history_table.assign(date=pd.to_datetime(self.history_table.datetime)).set_index('date').resample('D').frozen.last().fillna(method='pad')
res_=res_[res_.index.isin(self.trade_range)]
return res_ |
def hold_table(self, datetime=None):
"到某一个时刻的持仓 如果给的是日期,则返回当日开盘前的持仓"
if datetime is None:
hold_available = self.history_table.set_index(
'datetime'
).sort_index().groupby('code').amount.sum().sort_index()
else:
hold_available = self.history_tab... |
def current_hold_price(self):
"""计算目前持仓的成本 用于模拟盘和实盘查询
Returns:
[type] -- [description]
"""
def weights(x):
n=len(x)
res=1
while res>0 or res<0:
res=sum(x[:n]['amount'])
n=n-1
... |
def hold_price(self, datetime=None):
"""计算持仓成本 如果给的是日期,则返回当日开盘前的持仓
Keyword Arguments:
datetime {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
"""
def weights(x):
if sum(x['amount']) != 0:
return... |
def hold_time(self, datetime=None):
"""持仓时间
Keyword Arguments:
datetime {[type]} -- [description] (default: {None})
"""
def weights(x):
if sum(x['amount']) != 0:
return pd.Timestamp(self.datetime
) - pd.to_datet... |
def reset_assets(self, init_cash=None):
'reset_history/cash/'
self.sell_available = copy.deepcopy(self.init_hold)
self.history = []
self.init_cash = init_cash
self.cash = [self.init_cash]
self.cash_available = self.cash[-1] |
def receive_simpledeal(
self,
code,
trade_price,
trade_amount,
trade_towards,
trade_time,
message=None,
order_id=None,
trade_id=None,
realorder_id=None
):
"""快速撮合成交接口
此接口是一个直接可以成... |
def receive_deal(
self,
code: str,
trade_id: str,
order_id: str,
realorder_id: str,
trade_price: float,
trade_amount: int,
trade_towards: int,
trade_time: str,
message=None
):
"""更新deal
... |
def send_order(
self,
code=None,
amount=None,
time=None,
towards=None,
price=None,
money=None,
order_model=None,
amount_model=None,
*args,
**kwargs
):
"""
ATTENTION CHA... |
def close_positions_order(self):
"""平仓单
Raises:
RuntimeError -- if ACCOUNT.RUNNING_ENVIRONMENT is NOT TZERO
Returns:
list -- list with order
"""
order_list = []
time = '{} 15:00:00'.format(self.date)
if self.running_environment == RUNNIN... |
def settle(self, settle_data = None):
"""
股票/期货的日结算
股票的结算: 结转股票可卖额度
T0的结算: 结转T0的额度
期货的结算: 结转静态资金
@2019-02-25 yutiansut
hold 在下面要进行大变化:
从 只计算数量 ==> 数量+成本+买入价 (携带更多信息)
基于history去计算hold ==> last_settle+ today_pos_change
"""
#pr... |
def on_bar(self, event):
'''
策略事件
:param event:
:return:
'''
'while updating the market data'
print(
"on_bar account {} ".format(self.account_cookie),
event.market_data.data
)
print(event.send_order)
try:
... |
def from_message(self, message):
"""resume the account from standard message
这个是从数据库恢复账户时需要的"""
self.account_cookie = message.get('account_cookie', None)
self.portfolio_cookie = message.get('portfolio_cookie', None)
self.user_cookie = message.get('user_cookie', None)
self... |
def from_otgdict(self, message):
"""[summary]
balance = static_balance + float_profit
"currency": "", # "CNY" (币种)
"pre_balance": float("nan"), # 9912934.78 (昨日账户权益)
"static_balance": float("nan"), # (静态权益)
"balance": float("nan"), # 9963216.55 (账户权益... |
def table(self):
"""
打印出account的内容
"""
return pd.DataFrame([
self.message,
]).set_index(
'account_cookie',
drop=False
).T |
def run(self, event):
'''
这个方法是被 QA_ThreadEngine 处理队列时候调用的, QA_Task 中 do 方法调用 run (在其它线程中)
'QA_WORKER method 重载'
:param event: 事件类型 QA_Event
:return:
'''
'QA_WORKER method'
if event.event_type is ACCOUNT_EVENT.SETTLE:
print('account_settle')
... |
def sync_account(self, sync_message):
"""同步账户
Arguments:
sync_message {[type]} -- [description]
"""
self.init_hold = sync_message['hold_available']
self.init_cash = sync_message['cash_available']
self.sell_available = copy.deepcopy(self.init_hold)
s... |
def change_cash(self, money):
"""
外部操作|高危|
"""
res = self.cash[-1] + money
if res >= 0:
# 高危操作
self.cash[-1] = res |
def get_history(self, start, end):
"""返回历史成交
Arguments:
start {str} -- [description]
end {str]} -- [description]
"""
return self.history_table.set_index(
'datetime',
drop=False
).loc[slice(pd.Timestamp(start),
p... |
def QA_SU_save_order(orderlist, client=DATABASE):
"""存储order_handler的order_status
Arguments:
orderlist {[dataframe]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
if isinstance(orderlist, pd.DataFrame):
collection = client.o... |
def QA_SU_save_deal(dealist, client=DATABASE):
"""存储order_handler的deal_status
Arguments:
dealist {[dataframe]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
if isinstance(dealist, pd.DataFrame):
collection = client.deal
... |
def QA_SU_save_order_queue(order_queue, client=DATABASE):
"""增量存储order_queue
Arguments:
order_queue {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
collection = client.order_queue
collection.create_index(
[('accoun... |
def SMA(Series, N, M=1):
"""
威廉SMA算法
本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index
2018/5/3
@yutiansut
"""
ret = []
i = 1
length = len(Series)
# 跳过X中前面几个 nan 值
while i < length:
if np.isnan(Series.iloc[i]):
i += 1
else:
break
preY = Series... |
def CROSS(A, B):
"""A<B then A>B A上穿B B下穿A
Arguments:
A {[type]} -- [description]
B {[type]} -- [description]
Returns:
[type] -- [description]
"""
var = np.where(A < B, 1, 0)
return (pd.Series(var, index=A.index).diff() < 0).apply(int) |
def COUNT(COND, N):
"""
2018/05/23 修改
参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429
现在返回的是series
"""
return pd.Series(np.where(COND, 1, 0), index=COND.index).rolling(N).sum() |
def LAST(COND, N1, N2):
"""表达持续性
从前N1日到前N2日一直满足COND条件
Arguments:
COND {[type]} -- [description]
N1 {[type]} -- [description]
N2 {[type]} -- [description]
"""
N2 = 1 if N2 == 0 else N2
assert N2 > 0
assert N1 > N2
return COND.iloc[-N1:-N2].all() |
def AVEDEV(Series, N):
"""
平均绝对偏差 mean absolute deviation
修正: 2018-05-25
之前用mad的计算模式依然返回的是单值
"""
return Series.rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True) |
def MACD(Series, FAST, SLOW, MID):
"""macd指标 仅适用于Series
对于DATAFRAME的应用请使用QA_indicator_macd
"""
EMAFAST = EMA(Series, FAST)
EMASLOW = EMA(Series, SLOW)
DIFF = EMAFAST - EMASLOW
DEA = EMA(DIFF, MID)
MACD = (DIFF - DEA) * 2
DICT = {'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD}
VAR = pd.Da... |
def BBI(Series, N1, N2, N3, N4):
'多空指标'
bbi = (MA(Series, N1) + MA(Series, N2) +
MA(Series, N3) + MA(Series, N4)) / 4
DICT = {'BBI': bbi}
VAR = pd.DataFrame(DICT)
return VAR |
def BARLAST(cond, yes=True):
"""支持MultiIndex的cond和DateTimeIndex的cond
条件成立 yes= True 或者 yes=1 根据不同的指标自己定
Arguments:
cond {[type]} -- [description]
"""
if isinstance(cond.index, pd.MultiIndex):
return len(cond)-cond.index.levels[0].tolist().index(cond[cond != yes].index[-1][0])-1
... |
def get_today_all(output='pd'):
"""today all
Returns:
[type] -- [description]
"""
data = []
today = str(datetime.date.today())
codes = QA_fetch_get_stock_list('stock').code.tolist()
bestip = select_best_ip()['stock']
for code in codes:
try:
l = QA_fetch_get_... |
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().code.unique().tolist... |
def QA_user_sign_in(username, password):
"""用户登陆
不使用 QAUSER库
只返回 TRUE/FALSE
"""
#user = QA_User(name= name, password=password)
cursor = DATABASE.user.find_one(
{'username': username, 'password': password})
if cursor is None:
QA_util_log_info('SOMETHING WRONG')
return ... |
def QA_user_sign_up(name, password, client):
"""只做check! 具体逻辑需要在自己的函数中实现
参见:QAWEBSERVER中的实现
Arguments:
name {[type]} -- [description]
password {[type]} -- [description]
client {[type]} -- [description]
Returns:
[type] -- [description]
"""
coll = client... |
def warp(self, order):
"""对order/market的封装
[description]
Arguments:
order {[type]} -- [description]
Returns:
[type] -- [description]
"""
# 因为成交模式对时间的封装
if order.order_model == ORDER_MODEL.MARKET:
if order.frequence is FREQ... |
def get_filename():
"""
get_filename
"""
return [(l[0],l[1]) for l in [line.strip().split(",") for line in requests.get(FINANCIAL_URL).text.strip().split('\n')]] |
def download_financialzip():
"""
会创建一个download/文件夹
"""
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(it... |
def get_df(self, data_file):
"""
读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考
https://github.com/rainx/pytdx/issues/133
:param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat
:return: pandas DataFrame格式的历史财务数据
"""
crawler = QAHistoryFinancialCrawle... |
def QA_fetch_get_sh_margin(date):
"""return shanghai margin data
Arguments:
date {str YYYY-MM-DD} -- date format
Returns:
pandas.DataFrame -- res for margin data
"""
if date in trade_date_sse:
data= pd.read_excel(_sh_url.format(QA_util_date_str2int
... |
def QA_fetch_get_sz_margin(date):
"""return shenzhen margin data
Arguments:
date {str YYYY-MM-DD} -- date format
Returns:
pandas.DataFrame -- res for margin data
"""
if date in trade_date_sse:
return pd.read_excel(_sz_url.format(date)).assign(date=date).assign(sse='sz') |
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():
... |
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() |
def login(self, broker_name, account_cookie, account=None):
"""login 登录到交易前置
2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态
Arguments:
broker_name {[type]} -- [description]
account_cookie {[type]} -- [description]
Keyword Arguments:
account {[type]} -- [descript... |
def sync_account(self, broker_name, account_cookie):
"""同步账户信息
Arguments:
broker_id {[type]} -- [description]
account_cookie {[type]} -- [description]
"""
try:
if isinstance(self.broker[broker_name], QA_BacktestBroker):
pass
... |
def _trade(self, event):
"内部函数"
print('==================================market enging: trade')
print(self.order_handler.order_queue.pending)
print('==================================')
self.order_handler._trade()
print('done') |
def settle_order(self):
"""交易前置结算
1. 回测: 交易队列清空,待交易队列标记SETTLE
2. 账户每日结算
3. broker结算更新
"""
if self.if_start_orderthreading:
self.order_handler.run(
QA_Event(
event_type=BROKER_EVENT.SETTLE,
event_queue=... |
def QA_util_to_json_from_pandas(data):
"""需要对于datetime 和date 进行转换, 以免直接被变成了时间戳"""
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')) |
def QA_util_code_tostr(code):
"""
将所有沪深股票从数字转化到6位的代码
因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1
"""
if isinstance(code, int):
return "{:>06d}".format(code)
if isinstance(code, str):
# 聚宽股票代码格式 '600000.XSHG'
# 掘金股票代码格式 'SHSE.600000'
# Wind股票代码格式 '600000.SH'
... |
def QA_util_code_tolist(code, auto_fill=True):
"""转换code==> list
Arguments:
code {[type]} -- [description]
Keyword Arguments:
auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True})
Returns:
[list] -- [description]
"""
if isinstance(code, str):
... |
def subscribe_strategy(
self,
strategy_id: str,
last: int,
today=datetime.date.today(),
cost_coins=10
):
"""订阅一个策略
会扣减你的积分
Arguments:
strategy_id {str} -- [description]
last {int} -- [description]
... |
def unsubscribe_stratgy(self, strategy_id):
"""取消订阅某一个策略
Arguments:
strategy_id {[type]} -- [description]
"""
today = datetime.date.today()
order_id = str(uuid.uuid1())
if strategy_id in self._subscribed_strategy.keys():
self._subscribed_strategy... |
def subscribing_strategy(self):
"""订阅一个策略
Returns:
[type] -- [description]
"""
res = self.subscribed_strategy.assign(
remains=self.subscribed_strategy.end.apply(
lambda x: pd.Timestamp(x) - pd.Timestamp(datetime.date.today())
)
... |
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
... |
def get_account(self, portfolio_cookie: str, account_cookie: str):
"""直接从二级目录拿到account
Arguments:
portfolio_cookie {str} -- [description]
account_cookie {str} -- [description]
Returns:
[type] -- [description]
"""
try:
return self... |
def generate_simpleaccount(self):
"""make a simple account with a easier way
如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account
如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account
"""
if len(self.portfolio_list.keys()) < 1:
po = self.new_portfolio()
els... |
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()
... |
def save(self):
"""
将QA_USER的信息存入数据库
ATTENTION:
在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save
"""
if self.wechat_id is not None:
self.client.update(
{'wechat_id': self.wechat_id},
{'$set': self.message},
... |
def sync(self):
"""基于账户/密码去sync数据库
"""
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... |
def reload(self, message):
"""恢复方法
Arguments:
message {[type]} -- [description]
"""
self.phone = message.get('phone')
self.level = message.get('level')
self.utype = message.get('utype')
self.coins = message.get('coins')
self.wechat_id = messa... |
def QA_util_format_date2str(cursor_date):
"""
对输入日期进行格式化处理,返回格式为 "%Y-%m-%d" 格式字符串
支持格式包括:
1. str: "%Y%m%d" "%Y%m%d%H%M%S", "%Y%m%d %H:%M:%S",
"%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H%M%S"
2. datetime.datetime
3. pd.Timestamp
4. int -> 自动在右边加 0 然后转换,譬如 '20190302093' --> "2019... |
def QA_util_get_next_trade_date(cursor_date, n=1):
"""
得到下 n 个交易日 (不包含当前交易日)
:param date:
:param n:
"""
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 = Q... |
def QA_util_get_pre_trade_date(cursor_date, n=1):
"""
得到前 n 个交易日 (不包含当前交易日)
:param date:
:param n:
"""
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(c... |
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]):
i... |
def QA_util_get_real_date(date, trade_list=trade_date_sse, towards=-1):
"""
获取真实的交易日期,其中,第三个参数towards是表示向前/向后推
towards=1 日期向后迭代
towards=-1 日期向前迭代
@ yutiansut
"""
date = str(date)[0:10]
if towards == 1:
while date not in trade_list:
date = str(
datetim... |
def QA_util_get_real_datelist(start, end):
"""
取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist
@yutiansut
2017/8/10
当start end中间没有交易日 返回None, None
@yutiansut/ 2017-12-19
"""
real_start = QA_util_get_real_date(start, trade_date_sse, 1)
real_end = QA_util_get_real_date(end, trade_... |
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 |
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 |
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... |
def QA_util_get_trade_datetime(dt=datetime.datetime.now()):
"""交易的真实日期
Returns:
[type] -- [description]
"""
#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_dat... |
def QA_util_get_order_datetime(dt):
"""委托的真实日期
Returns:
[type] -- [description]
"""
#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)
... |
def QA_util_future_to_tradedatetime(real_datetime):
"""输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换
Arguments:
real_datetime {[type]} -- [description]
Returns:
[type] -- [description]
"""
if len(str(real_datetime)) >= 19:
dt = datetime.datetime.strptime(
str(real_dat... |
def QA_util_future_to_realdatetime(trade_datetime):
"""输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换
Arguments:
trade_datetime {[type]} -- [description]
Returns:
[type] -- [description]
"""
if len(str(trade_datetime)) == 19:
dt = datetime.datetime.strptime(
str(trade_datetime)... |
def QA_util_make_hour_index(day, type_='1h'):
"""创建股票的小时线的index
Arguments:
day {[type]} -- [description]
Returns:
[type] -- [description]
"""
if QA_util_if_trade(day) is True:
return pd.date_range(
str(day) + ' 09:30:00',
str(day) + ' 11:30:00',
... |
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,
... |
def QA_util_save_csv(data, name, column=None, location=None):
# 重写了一下保存的模式
# 增加了对于可迭代对象的判断 2017/8/10
"""
QA_util_save_csv(data,name,column,location)
将list保存成csv
第一个参数是list
第二个参数是要保存的名字
第三个参数是行的名称(可选)
第四个是保存位置(可选)
@yutiansut
"""
assert isinstance(data, list)
if locat... |
def query_positions(self, accounts):
"""查询现金和持仓
Arguments:
accounts {[type]} -- [description]
Returns:
dict-- {'cash_available':xxx,'hold_available':xxx}
"""
try:
data = self.call("positions", {'client': accounts})
if data is not ... |
def query_clients(self):
"""查询clients
Returns:
[type] -- [description]
"""
try:
data = self.call("clients", {'client': 'None'})
if len(data) > 0:
return pd.DataFrame(data).drop(
['commandLine',
... |
def query_orders(self, accounts, status='filled'):
"""查询订单
Arguments:
accounts {[type]} -- [description]
Keyword Arguments:
status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})
Returns:
[type] -- [description]
"""
try:
... |
def send_order(
self,
accounts,
code='000001',
price=9,
amount=100,
order_direction=ORDER_DIRECTION.BUY,
order_model=ORDER_MODEL.LIMIT
):
"""[summary]
Arguments:
accounts {[type]} -- [description]
... |
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') |
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') |
def QA_SU_save_stock_terminated(client=DATABASE):
'''
获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。
collection:
code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期
:param client:
:return: None
'''
# 🛠todo 已经失效从wind 资讯里获取
# 这个函数已经失效
print("!!! tushare 这个函数已经失效!!!")
df = QATs.get... |
def QA_SU_save_stock_info_tushare(client=DATABASE):
'''
获取 股票的 基本信息,包含股票的如下信息
code,代码
name,名称
industry,所属行业
area,地区
pe,市盈率
outstanding,流通股本(亿)
totals,总股本(亿)
totalAssets,总资产(万)
liquidAssets,流动资产
fixedAssets,固定资产
reserved... |
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... |
def QA_util_dict_remove_key(dicts, key):
"""
输入一个dict 返回删除后的
"""
if isinstance(key, list):
for item in key:
try:
dicts.pop(item)
except:
pass
else:
try:
dicts.pop(key)
except:
pass
return dic... |
def QA_util_sql_async_mongo_setting(uri='mongodb://localhost:27017/quantaxis'):
"""异步mongo示例
Keyword Arguments:
uri {str} -- [description] (default: {'mongodb://localhost:27017/quantaxis'})
Returns:
[type] -- [description]
"""
# loop = asyncio.new_event_loop()
# asyncio.set_eve... |
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
... |
def drop_account(self, account_cookie):
"""删除一个account
Arguments:
account_cookie {[type]} -- [description]
Raises:
RuntimeError -- [description]
"""
if account_cookie in self.account_list:
res = self.account_list.remove(account_cookie)
... |
def new_account(
self,
account_cookie=None,
init_cash=1000000,
market_type=MARKET_TYPE.STOCK_CN,
*args,
**kwargs
):
"""创建一个新的Account
Keyword Arguments:
account_cookie {[type]} -- [description] (default: {None})
... |
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=c... |
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)
e... |
def message(self):
"""portfolio 的cookie
"""
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,
'histo... |
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
):
... |
def save(self):
"""存储过程
"""
self.client.update(
{
'portfolio_cookie': self.portfolio_cookie,
'user_cookie': self.user_cookie
},
{'$set': self.message},
upsert=True
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.