text stringlengths 81 112k |
|---|
现金的table
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]))
).assign(account_cookie=self.account_cookie) # .sort_values('datetime')
return _cash.set_index(['datetime', 'account_cookie'], drop=False)
"""
实验性质
@2018-06-09
# 对于账户持仓的分解
1. 真实持仓hold:
正常模式/TZero模式:
hold = 历史持仓(init_hold)+ 初始化账户后发生的所有交易导致的持仓(hold_available)
动态持仓(初始化账户后的持仓)hold_available:
self.history 计算而得
2. 账户的可卖额度(sell_available)
正常模式:
sell_available
结算前: init_hold+ 买卖交易(卖-)
结算后: init_hold+ 买卖交易(买+ 卖-)
TZero模式:
sell_available
结算前: init_hold - 买卖交易占用的额度(abs(买+ 卖-))
结算过程 是为了补平(等于让hold={})
结算后: init_hold
""" |
真实持仓
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() |
每次交易的pivot表
Returns:
pd.DataFrame
此处的pivot_table一定要用np.sum
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',
aggfunc=np.sum
).fillna(0).sort_index() |
每日交易结算时的现金表
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_index=True,right_index=True)
res_=res_.ffill().fillna(self.init_cash).drop(['predrop','datetime','account_cookie'], axis=1).reset_index().set_index(['date'],drop=False).sort_index()
res_=res_[res_.index.isin(self.trade_range)]
return res_ |
每日交易结算时的持仓表
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]).date
)
data.date = pd.to_datetime(data.date)
data = data.set_index(['date', 'account_cookie'])
res = data[~data.index.duplicated(keep='last')].sort_index()
# 这里会导致股票停牌时的持仓也被计算 但是计算market_value的时候就没了
le=pd.DataFrame(pd.Series(data=None, index=pd.to_datetime(self.trade_range_max).set_names('date'), name='predrop'))
ri=res.reset_index().set_index('date')
res_=pd.merge(le,ri,how='left',left_index=True,right_index=True)
res_=res_.ffill().fillna(0).drop(['predrop','account_cookie'], axis=1).reset_index().set_index(['date']).sort_index()
res_=res_[res_.index.isin(self.trade_range)]
return res_ |
每日交易结算时的持仓表
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_table.set_index(
'datetime'
).sort_index().loc[:datetime].groupby('code'
).amount.sum().sort_index()
return pd.concat([self.init_hold,
hold_available]).groupby('code').sum().sort_index(
).apply(lambda x: x if x > 0 else None).dropna() |
计算目前持仓的成本 用于模拟盘和实盘查询
Returns:
[type] -- [description]
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
x=x[n+1:]
if sum(x['amount']) != 0:
return np.average(
x['price'],
weights=x['amount'],
returned=True
)
else:
return np.nan
return self.history_table.set_index(
'datetime',
drop=False
).sort_index().groupby('code').apply(weights).dropna() |
计算持仓成本 如果给的是日期,则返回当日开盘前的持仓
Keyword Arguments:
datetime {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
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 np.average(
x['price'],
weights=x['amount'],
returned=True
)
else:
return np.nan
if datetime is None:
return self.history_table.set_index(
'datetime',
drop=False
).sort_index().groupby('code').apply(weights).dropna()
else:
return self.history_table.set_index(
'datetime',
drop=False
).sort_index().loc[:datetime].groupby('code').apply(weights
).dropna() |
持仓时间
Keyword Arguments:
datetime {[type]} -- [description] (default: {None})
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_datetime(x.datetime.max())
else:
return np.nan
if datetime is None:
return self.history_table.set_index(
'datetime',
drop=False
).sort_index().groupby('code').apply(weights).dropna()
else:
return self.history_table.set_index(
'datetime',
drop=False
).sort_index().loc[:datetime].groupby('code').apply(weights
).dropna() |
reset_history/cash/
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] |
快速撮合成交接口
此接口是一个直接可以成交的接口, 所以务必确保给出的信息是可以成交的
此接口涉及的是
1. 股票/期货的成交
2. 历史记录的增加
3. 现金/持仓/冻结资金的处理
Arguments:
code {[type]} -- [description]
trade_price {[type]} -- [description]
trade_amount {[type]} -- [description]
trade_towards {[type]} -- [description]
trade_time {[type]} -- [description]
Keyword Arguments:
message {[type]} -- [description] (default: {None})
2018/11/7 @yutiansut
修复一个bug: 在直接使用该快速撮合接口的时候, 期货卖出会扣减保证金, 买回来的时候应该反算利润
如 3800卖空 3700买回平仓 应为100利润
@2018-12-31 保证金账户ok
@2019/1/3 一些重要的意思
frozen = self.market_preset.get_frozen(code) # 保证金率
unit = self.market_preset.get_unit(code) # 合约乘数
raw_trade_money = trade_price*trade_amount*market_towards # 总市值
value = raw_trade_money * unit # 合约总价值
trade_money = value * frozen # 交易保证金
def receive_simpledeal(
self,
code,
trade_price,
trade_amount,
trade_towards,
trade_time,
message=None,
order_id=None,
trade_id=None,
realorder_id=None
):
"""快速撮合成交接口
此接口是一个直接可以成交的接口, 所以务必确保给出的信息是可以成交的
此接口涉及的是
1. 股票/期货的成交
2. 历史记录的增加
3. 现金/持仓/冻结资金的处理
Arguments:
code {[type]} -- [description]
trade_price {[type]} -- [description]
trade_amount {[type]} -- [description]
trade_towards {[type]} -- [description]
trade_time {[type]} -- [description]
Keyword Arguments:
message {[type]} -- [description] (default: {None})
2018/11/7 @yutiansut
修复一个bug: 在直接使用该快速撮合接口的时候, 期货卖出会扣减保证金, 买回来的时候应该反算利润
如 3800卖空 3700买回平仓 应为100利润
@2018-12-31 保证金账户ok
@2019/1/3 一些重要的意思
frozen = self.market_preset.get_frozen(code) # 保证金率
unit = self.market_preset.get_unit(code) # 合约乘数
raw_trade_money = trade_price*trade_amount*market_towards # 总市值
value = raw_trade_money * unit # 合约总价值
trade_money = value * frozen # 交易保证金
"""
self.datetime = trade_time
if realorder_id in self.finishedOrderid:
pass
else:
self.finishedOrderid.append(realorder_id)
market_towards = 1 if trade_towards > 0 else -1
# value 合约价值 unit 合约乘数
if self.allow_margin:
frozen = self.market_preset.get_frozen(code) # 保证金率
unit = self.market_preset.get_unit(code) # 合约乘数
raw_trade_money = trade_price * trade_amount * market_towards # 总市值
value = raw_trade_money * unit # 合约总价值
trade_money = value * frozen # 交易保证金
else:
trade_money = trade_price * trade_amount * market_towards
raw_trade_money = trade_money
value = trade_money
unit = 1
frozen = 1
# 计算费用
# trade_price
if self.market_type == MARKET_TYPE.FUTURE_CN:
# 期货不收税
# 双边手续费 也没有最小手续费限制
commission_fee_preset = self.market_preset.get_code(code)
if trade_towards in [ORDER_DIRECTION.BUY_OPEN,
ORDER_DIRECTION.BUY_CLOSE,
ORDER_DIRECTION.SELL_CLOSE,
ORDER_DIRECTION.SELL_OPEN]:
commission_fee = commission_fee_preset['commission_coeff_pervol'] * trade_amount + \
commission_fee_preset['commission_coeff_peramount'] * \
abs(value)
elif trade_towards in [ORDER_DIRECTION.BUY_CLOSETODAY,
ORDER_DIRECTION.SELL_CLOSETODAY]:
commission_fee = commission_fee_preset['commission_coeff_today_pervol'] * trade_amount + \
commission_fee_preset['commission_coeff_today_peramount'] * \
abs(value)
tax_fee = 0 # 买入不收印花税
elif self.market_type == MARKET_TYPE.STOCK_CN:
commission_fee = self.commission_coeff * \
abs(trade_money)
commission_fee = 5 if commission_fee < 5 else commission_fee
if int(trade_towards) > 0:
tax_fee = 0 # 买入不收印花税
else:
tax_fee = self.tax_coeff * abs(trade_money)
# 结算交易
if self.cash[-1] > trade_money + commission_fee + tax_fee:
self.time_index_max.append(trade_time)
# TODO: 目前还不支持期货的锁仓
if self.allow_sellopen:
if trade_towards in [ORDER_DIRECTION.BUY_OPEN,
ORDER_DIRECTION.SELL_OPEN]:
# 开仓单占用现金 计算avg
# 初始化
if code in self.frozen.keys():
if trade_towards in self.frozen[code].keys():
pass
else:
self.frozen[code][str(trade_towards)] = {
'money': 0,
'amount': 0,
'avg_price': 0
}
else:
self.frozen[code] = {
str(ORDER_DIRECTION.BUY_OPEN): {
'money': 0,
'amount': 0,
'avg_price': 0
},
str(ORDER_DIRECTION.SELL_OPEN): {
'money': 0,
'amount': 0,
'avg_price': 0
}
}
"""[summary]
# frozen的计算
# money 冻结的资金
# amount 冻结的数量
2018-12-31
"""
self.frozen[code][str(trade_towards)]['money'] = (
(
self.frozen[code][str(trade_towards)]['money'] *
self.frozen[code][str(trade_towards)]['amount']
) + abs(trade_money)
) / (
self.frozen[code][str(trade_towards)]['amount'] +
trade_amount
)
self.frozen[code][str(trade_towards)]['avg_price'] = (
(
self.frozen[code][str(trade_towards)]['avg_price'] *
self.frozen[code][str(trade_towards)]['amount']
) + abs(raw_trade_money)
) / (
self.frozen[code][str(trade_towards)]['amount'] +
trade_amount
)
self.frozen[code][str(trade_towards)]['amount'] += trade_amount
self.cash.append(
self.cash[-1] - abs(trade_money) - commission_fee -
tax_fee
)
elif trade_towards in [ORDER_DIRECTION.BUY_CLOSE, ORDER_DIRECTION.BUY_CLOSETODAY,
ORDER_DIRECTION.SELL_CLOSE, ORDER_DIRECTION.SELL_CLOSETODAY]:
# 平仓单释放现金
# if trade_towards == ORDER_DIRECTION.BUY_CLOSE:
# 卖空开仓 平仓买入
# self.cash
if trade_towards in [ORDER_DIRECTION.BUY_CLOSE, ORDER_DIRECTION.BUY_CLOSETODAY]: # 买入平仓 之前是空开
# self.frozen[code][ORDER_DIRECTION.SELL_OPEN]['money'] -= trade_money
self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['amount'] -= trade_amount
frozen_part = self.frozen[code][
str(ORDER_DIRECTION.SELL_OPEN)]['money'] * trade_amount
# 账户的现金+ 冻结的的释放 + 买卖价差* 杠杆
self.cash.append(
self.cash[-1] + frozen_part +
(frozen_part - trade_money) / frozen -
commission_fee - tax_fee
)
if self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['amount'] == 0:
self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['money'] = 0
self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['avg_price'] = 0
elif trade_towards in [ORDER_DIRECTION.SELL_CLOSE, ORDER_DIRECTION.SELL_CLOSETODAY]: # 卖出平仓 之前是多开
# self.frozen[code][ORDER_DIRECTION.BUY_OPEN]['money'] -= trade_money
self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['amount'] -= trade_amount
frozen_part = self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['money'] * trade_amount
self.cash.append(
self.cash[-1] + frozen_part +
(abs(trade_money) - frozen_part) / frozen -
commission_fee - tax_fee
)
if self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['amount'] == 0:
self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['money'] = 0
self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['avg_price'] = 0
else: # 不允许卖空开仓的==> 股票
self.cash.append(
self.cash[-1] - trade_money - tax_fee - commission_fee
)
if self.allow_t0 or trade_towards == ORDER_DIRECTION.SELL:
self.sell_available[code] = self.sell_available.get(
code,
0
) + trade_amount * market_towards
self.buy_available = self.sell_available
self.cash_available = self.cash[-1]
frozen_money = abs(trade_money) if trade_towards in [
ORDER_DIRECTION.BUY_OPEN,
ORDER_DIRECTION.SELL_OPEN
] else 0
self.history.append(
[
str(trade_time),
code,
trade_price,
market_towards * trade_amount,
self.cash[-1],
order_id,
realorder_id,
trade_id,
self.account_cookie,
commission_fee,
tax_fee,
message,
frozen_money,
trade_towards
]
)
else:
print('ALERT MONEY NOT ENOUGH!!!')
print(self.cash[-1])
self.cash_available = self.cash[-1] |
更新deal
Arguments:
code {str} -- [description]
trade_id {str} -- [description]
order_id {str} -- [description]
realorder_id {str} -- [description]
trade_price {float} -- [description]
trade_amount {int} -- [description]
trade_towards {int} -- [description]
trade_time {str} -- [description]
Returns:
[type] -- [description]
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
Arguments:
code {str} -- [description]
trade_id {str} -- [description]
order_id {str} -- [description]
realorder_id {str} -- [description]
trade_price {float} -- [description]
trade_amount {int} -- [description]
trade_towards {int} -- [description]
trade_time {str} -- [description]
Returns:
[type] -- [description]
"""
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!receive deal')
trade_time = str(trade_time)
code = str(code)
trade_price = float(trade_price)
trade_towards = int(trade_towards)
realorder_id = str(realorder_id)
trade_id = str(trade_id)
trade_amount = int(trade_amount)
order_id = str(order_id)
market_towards = 1 if trade_towards > 0 else -1
"""2019/01/03 直接使用快速撮合接口了
2333 这两个接口现在也没啥区别了....
太绝望了
"""
self.receive_simpledeal(
code,
trade_price,
trade_amount,
trade_towards,
trade_time,
message=message,
order_id=order_id,
trade_id=trade_id,
realorder_id=realorder_id
) |
ATTENTION CHANGELOG 1.0.28
修改了Account的send_order方法, 区分按数量下单和按金额下单两种方式
- AMOUNT_MODEL.BY_PRICE ==> AMOUNT_MODEL.BY_MONEY # 按金额下单
- AMOUNT_MODEL.BY_AMOUNT # 按数量下单
在按金额下单的时候,应给予 money参数
在按数量下单的时候,应给予 amount参数
python code:
Account=QA.QA_Account()
Order_bymoney=Account.send_order(code='000001',
price=11,
money=0.3*Account.cash_available,
time='2018-05-09',
towards=QA.ORDER_DIRECTION.BUY,
order_model=QA.ORDER_MODEL.MARKET,
amount_model=QA.AMOUNT_MODEL.BY_MONEY
)
Order_byamount=Account.send_order(code='000001',
price=11,
amount=100,
time='2018-05-09',
towards=QA.ORDER_DIRECTION.BUY,
order_model=QA.ORDER_MODEL.MARKET,
amount_model=QA.AMOUNT_MODEL.BY_AMOUNT
)
:param code: 证券代码
:param amount: 买卖 数量多数股
:param time: Timestamp 对象 下单时间
:param towards: int , towards>0 买入 towards<0 卖出
:param price: 买入,卖出 标的证券的价格
:param money: 买卖 价格
:param order_model: 类型 QA.ORDER_MODE
:param amount_model:类型 QA.AMOUNT_MODEL
:return: QA_Order | False
@2018/12/23
send_order 是QA的标准返回, 如需对接其他接口, 只需要对于QA_Order做适配即可
@2018/12/27
在判断账户为期货账户(及 允许双向交易)
@2018/12/30 保证金账户的修改
1. 保证金账户冻结的金额
2. 保证金账户的结算
3. 保证金账户的判断
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 CHANGELOG 1.0.28
修改了Account的send_order方法, 区分按数量下单和按金额下单两种方式
- AMOUNT_MODEL.BY_PRICE ==> AMOUNT_MODEL.BY_MONEY # 按金额下单
- AMOUNT_MODEL.BY_AMOUNT # 按数量下单
在按金额下单的时候,应给予 money参数
在按数量下单的时候,应给予 amount参数
python code:
Account=QA.QA_Account()
Order_bymoney=Account.send_order(code='000001',
price=11,
money=0.3*Account.cash_available,
time='2018-05-09',
towards=QA.ORDER_DIRECTION.BUY,
order_model=QA.ORDER_MODEL.MARKET,
amount_model=QA.AMOUNT_MODEL.BY_MONEY
)
Order_byamount=Account.send_order(code='000001',
price=11,
amount=100,
time='2018-05-09',
towards=QA.ORDER_DIRECTION.BUY,
order_model=QA.ORDER_MODEL.MARKET,
amount_model=QA.AMOUNT_MODEL.BY_AMOUNT
)
:param code: 证券代码
:param amount: 买卖 数量多数股
:param time: Timestamp 对象 下单时间
:param towards: int , towards>0 买入 towards<0 卖出
:param price: 买入,卖出 标的证券的价格
:param money: 买卖 价格
:param order_model: 类型 QA.ORDER_MODE
:param amount_model:类型 QA.AMOUNT_MODEL
:return: QA_Order | False
@2018/12/23
send_order 是QA的标准返回, 如需对接其他接口, 只需要对于QA_Order做适配即可
@2018/12/27
在判断账户为期货账户(及 允许双向交易)
@2018/12/30 保证金账户的修改
1. 保证金账户冻结的金额
2. 保证金账户的结算
3. 保证金账户的判断
"""
wrong_reason = None
assert code is not None and time is not None and towards is not None and order_model is not None and amount_model is not None
# 🛠todo 移到Utils类中, 时间转换
# date 字符串 2011-10-11 长度10
date = str(time)[0:10] if len(str(time)) == 19 else str(time)
# time 字符串 20011-10-11 09:02:00 长度 19
time = str(time) if len(str(time)) == 19 else '{} 09:31:00'.format(
str(time)[0:10]
)
# 🛠todo 移到Utils类中, amount_to_money 成交量转金额
# BY_MONEY :: amount --钱 如10000元 因此 by_money里面 需要指定价格,来计算实际的股票数
# by_amount :: amount --股数 如10000股
if self.allow_margin:
amount = amount if amount_model is AMOUNT_MODEL.BY_AMOUNT else int(
money / (
self.market_preset.get_unit(code) *
self.market_preset.get_frozen(code) * price *
(1 + self.commission_coeff)
) / 100
) * 100
else:
amount = amount if amount_model is AMOUNT_MODEL.BY_AMOUNT else int(
money / (price * (1 + self.commission_coeff)) / 100
) * 100
# 🛠todo 移到Utils类中, money_to_amount 金额转成交量
if self.allow_margin:
money = amount * price * self.market_preset.get_unit(code)*self.market_preset.get_frozen(code) * \
(1+self.commission_coeff) if amount_model is AMOUNT_MODEL.BY_AMOUNT else money
else:
money = amount * price * \
(1+self.commission_coeff) if amount_model is AMOUNT_MODEL.BY_AMOUNT else money
# flag 判断买卖 数量和价格以及买卖方向是否正确
flag = False
assert (int(towards) != 0)
if int(towards) in [1, 2, 3]:
# 是买入的情况(包括买入.买开.买平)
if self.cash_available >= money:
if self.market_type == MARKET_TYPE.STOCK_CN: # 如果是股票 买入的时候有100股的最小限制
amount = int(amount / 100) * 100
self.cash_available -= money
flag = True
if self.running_environment == RUNNING_ENVIRONMENT.TZERO:
if abs(self.buy_available.get(code, 0)) >= amount:
flag = True
self.cash_available -= money
self.buy_available[code] -= amount
else:
flag = False
wrong_reason = 'T0交易买入超出限额'
if self.market_type == MARKET_TYPE.FUTURE_CN:
# 如果有负持仓-- 允许卖空的时候
if towards == 3: # 多平
_hold = self.sell_available.get(code, 0)
# 假设有负持仓:
# amount为下单数量 如 账户原先-3手 现在平1手
#left_amount = amount+_hold if _hold < 0 else amount
_money = abs(
float(amount * price * (1 + self.commission_coeff))
)
print(_hold)
if self.cash_available >= _money:
if _hold < 0:
self.cash_available -= _money
flag = True
else:
wrong_reason = '空单仓位不足'
else:
wrong_reason = '平多剩余资金不够'
if towards == 2:
self.cash_available -= money
flag = True
else:
wrong_reason = 'QAACCOUNT: 可用资金不足 cash_available {} code {} time {} amount {} towards {}'.format(
self.cash_available,
code,
time,
amount,
towards
)
elif int(towards) in [-1, -2, -3]:
# 是卖出的情况(包括卖出,卖出开仓allow_sellopen如果允许. 卖出平仓)
# print(self.sell_available[code])
_hold = self.sell_available.get(code, 0) # _hold 是你的持仓
# 如果你的hold> amount>0
# 持仓数量>卖出数量
if _hold >= amount:
self.sell_available[code] -= amount
# towards = ORDER_DIRECTION.SELL
flag = True
# 如果持仓数量<卖出数量
else:
# 如果是允许卖空开仓 实际计算时 先减去持仓(正持仓) 再计算 负持仓 就按原先的占用金额计算
if self.allow_sellopen and towards == -2:
if self.cash_available >= money: # 卖空的市值小于现金(有担保的卖空), 不允许裸卖空
# self.cash_available -= money
flag = True
else:
print('sellavailable', _hold)
print('amount', amount)
print('aqureMoney', money)
print('cash', self.cash_available)
wrong_reason = "卖空资金不足/不允许裸卖空"
else:
wrong_reason = "卖出仓位不足"
if flag and (amount > 0):
_order = QA_Order(
user_cookie=self.user_cookie,
strategy=self.strategy_name,
frequence=self.frequence,
account_cookie=self.account_cookie,
code=code,
market_type=self.market_type,
date=date,
datetime=time,
sending_time=time,
callback=self.receive_deal,
amount=amount,
price=price,
order_model=order_model,
towards=towards,
money=money,
broker=self.broker,
amount_model=amount_model,
commission_coeff=self.commission_coeff,
tax_coeff=self.tax_coeff,
*args,
**kwargs
) # init
# 历史委托order状态存储, 保存到 QA_Order 对象中的队列中
self.datetime = time
self.orders.insert_order(_order)
return _order
else:
print(
'ERROR : CODE {} TIME {} AMOUNT {} TOWARDS {}'.format(
code,
time,
amount,
towards
)
)
print(wrong_reason)
return False |
平仓单
Raises:
RuntimeError -- if ACCOUNT.RUNNING_ENVIRONMENT is NOT TZERO
Returns:
list -- list with order
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 == RUNNING_ENVIRONMENT.TZERO:
for code, amount in self.hold_available.iteritems():
order = False
if amount < 0:
# 先卖出的单子 买平
order = self.send_order(
code=code,
price=0,
amount=abs(amount),
time=time,
towards=ORDER_DIRECTION.BUY,
order_model=ORDER_MODEL.CLOSE,
amount_model=AMOUNT_MODEL.BY_AMOUNT,
)
elif amount > 0:
# 先买入的单子, 卖平
order = self.send_order(
code=code,
price=0,
amount=abs(amount),
time=time,
towards=ORDER_DIRECTION.SELL,
order_model=ORDER_MODEL.CLOSE,
amount_model=AMOUNT_MODEL.BY_AMOUNT
)
if order:
order_list.append(order)
return order_list
else:
raise RuntimeError(
'QAACCOUNT with {} environments cannot use this methods'.format(
self.running_environment
)
) |
股票/期货的日结算
股票的结算: 结转股票可卖额度
T0的结算: 结转T0的额度
期货的结算: 结转静态资金
@2019-02-25 yutiansut
hold 在下面要进行大变化:
从 只计算数量 ==> 数量+成本+买入价 (携带更多信息)
基于history去计算hold ==> last_settle+ today_pos_change
def settle(self, settle_data = None):
"""
股票/期货的日结算
股票的结算: 结转股票可卖额度
T0的结算: 结转T0的额度
期货的结算: 结转静态资金
@2019-02-25 yutiansut
hold 在下面要进行大变化:
从 只计算数量 ==> 数量+成本+买入价 (携带更多信息)
基于history去计算hold ==> last_settle+ today_pos_change
"""
#print('FROM QUANTAXIS QA_ACCOUNT: account settle')
if self.running_environment == RUNNING_ENVIRONMENT.TZERO and self.hold_available.sum(
) != 0:
raise RuntimeError(
'QAACCOUNT: 该T0账户未当日仓位,请平仓 {}'.format(
self.hold_available.to_dict()
)
)
if self.market_type == MARKET_TYPE.FUTURE_CN:
# 增加逐日盯市制度
self.static_balance['frozen'].append(
sum(
[
rx['money'] * rx['amount']
for var in self.frozen.values()
for rx in var.values()
]
)
)
self.static_balance['cash'].append(self.cash[-1])
self.static_balance['hold'].append(self.hold.to_dict())
self.static_balance['date'].append(self.date)
"""静态权益的结算
只关心开仓价/ 不做盯市制度
动态权益的结算需要关心
"""
self.static_balance['static_assets'].append(
self.static_balance['cash'][-1] +
self.static_balance['frozen'][-1]
)
self.sell_available = self.hold
self.buy_available = self.hold
self.cash_available = self.cash[-1]
self.datetime = '{} 09:30:00'.format(
QA_util_get_next_day(self.date)
) if self.date is not None else None |
策略事件
:param event:
:return:
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:
for code in event.market_data.code:
if self.sell_available.get(code, 0) > 0:
print('可以卖出 {}'.format(self._currenttime))
event.send_order(
account_cookie=self.account_cookie,
amount=self.sell_available[code],
amount_model=AMOUNT_MODEL.BY_AMOUNT,
time=self.current_time,
code=code,
price=0,
order_model=ORDER_MODEL.MARKET,
towards=ORDER_DIRECTION.SELL,
market_type=self.market_type,
frequence=self.frequence,
broker_name=self.broker
)
else:
print('{} 无仓位, 买入{}'.format(self._currenttime, code))
event.send_order(
account_cookie=self.account_cookie,
amount=100,
amount_model=AMOUNT_MODEL.BY_AMOUNT,
time=self.current_time,
code=code,
price=0,
order_model=ORDER_MODEL.MARKET,
towards=ORDER_DIRECTION.BUY,
market_type=self.market_type,
frequence=self.frequence,
broker_name=self.broker
)
except Exception as e:
print(e) |
resume the account from standard message
这个是从数据库恢复账户时需要的
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.broker = message.get('broker', None)
self.market_type = message.get('market_type', None)
self.strategy_name = message.get('strategy_name', None)
self._currenttime = message.get('current_time', None)
self.allow_sellopen = message.get('allow_sellopen', False)
self.allow_margin = message.get('allow_margin', False)
self.allow_t0 = message.get('allow_t0', False)
self.margin_level = message.get('margin_level', False)
self.frequence = message.get('frequence', FREQUENCE.FIFTEEN_MIN) #默认15min
self.init_cash = message.get(
'init_cash',
message.get('init_assets',
1000000)
) # 兼容修改
self.init_hold = pd.Series(message.get('init_hold', {}), name='amount')
self.init_hold.index.name = 'code'
self.commission_coeff = message.get('commission_coeff', 0.00015)
self.tax_coeff = message.get('tax_coeff', 0.0015)
self.history = message['history']
self.cash = message['cash']
self.time_index_max = message['trade_index']
self.running_time = message.get('running_time', None)
self.quantaxis_version = message.get('quantaxis_version', None)
self.running_environment = message.get(
'running_environment',
RUNNING_ENVIRONMENT.BACKETEST
)
self.frozen = message.get('frozen', {})
self.finishedOrderid = message.get('finished_id', [])
self.settle()
return self |
[summary]
balance = static_balance + float_profit
"currency": "", # "CNY" (币种)
"pre_balance": float("nan"), # 9912934.78 (昨日账户权益)
"static_balance": float("nan"), # (静态权益)
"balance": float("nan"), # 9963216.55 (账户权益)
"available": float("nan"), # 9480176.15 (可用资金)
"float_profit": float("nan"), # 8910.0 (浮动盈亏)
"position_profit": float("nan"), # 1120.0(持仓盈亏)
"close_profit": float("nan"), # -11120.0 (本交易日内平仓盈亏)
"frozen_margin": float("nan"), # 0.0(冻结保证金)
"margin": float("nan"), # 11232.23 (保证金占用)
"frozen_commission": float("nan"), # 0.0 (冻结手续费)
"commission": float("nan"), # 123.0 (本交易日内交纳的手续费)
"frozen_premium": float("nan"), # 0.0 (冻结权利金)
"premium": float("nan"), # 0.0 (本交易日内交纳的权利金)
"deposit": float("nan"), # 1234.0 (本交易日内的入金金额)
"withdraw": float("nan"), # 890.0 (本交易日内的出金金额)
"risk_ratio": float("nan"), # 0.048482375 (风险度)
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 (账户权益)
"available": float("nan"), # 9480176.15 (可用资金)
"float_profit": float("nan"), # 8910.0 (浮动盈亏)
"position_profit": float("nan"), # 1120.0(持仓盈亏)
"close_profit": float("nan"), # -11120.0 (本交易日内平仓盈亏)
"frozen_margin": float("nan"), # 0.0(冻结保证金)
"margin": float("nan"), # 11232.23 (保证金占用)
"frozen_commission": float("nan"), # 0.0 (冻结手续费)
"commission": float("nan"), # 123.0 (本交易日内交纳的手续费)
"frozen_premium": float("nan"), # 0.0 (冻结权利金)
"premium": float("nan"), # 0.0 (本交易日内交纳的权利金)
"deposit": float("nan"), # 1234.0 (本交易日内的入金金额)
"withdraw": float("nan"), # 890.0 (本交易日内的出金金额)
"risk_ratio": float("nan"), # 0.048482375 (风险度)
"""
self.allow_margin = True
self.allow_sellopen = True
self.allow_t0 = True
self.account_cookie = message['accounts']['user_id']
# 可用资金
self.cash_available = message['accounts']['available']
self.balance = message['accounts']['balance']
# 都是在结算的时候计算的
# 昨日权益/静态权益 ==> 这两个是一样的
self.static_balance = message['accounts']['static_balance']
self.pre_balance = message['accounts']['pre_balance']
# 平仓盈亏
self.close_profit = message['accounts']['close_profit']
# 持仓盈亏
self.position_profit = message['accounts']['position_profit']
# 动态权益
self.float_profit = message['accounts']['float_profit']
# 占用保证金
self.margin = message['accounts']['margin']
self.commission = message['accounts']['commission'] |
打印出account的内容
def table(self):
"""
打印出account的内容
"""
return pd.DataFrame([
self.message,
]).set_index(
'account_cookie',
drop=False
).T |
这个方法是被 QA_ThreadEngine 处理队列时候调用的, QA_Task 中 do 方法调用 run (在其它线程中)
'QA_WORKER method 重载'
:param event: 事件类型 QA_Event
:return:
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')
self.settle()
# elif event.event_type is ACCOUNT_EVENT.UPDATE:
# self.receive_deal(event.message)
elif event.event_type is ACCOUNT_EVENT.MAKE_ORDER:
"""generate order
if callback callback the order
if not return back the order
"""
data = self.send_order(
code=event.code,
amount=event.amount,
time=event.time,
amount_model=event.amount_model,
towards=event.towards,
price=event.price,
order_model=event.order_model
)
if event.callback:
event.callback(data)
else:
return data
elif event.event_type is ENGINE_EVENT.UPCOMING_DATA:
"""update the market_data
1. update the inside market_data struct
2. tell the on_bar methods
# 这样有点慢
"""
self._currenttime = event.market_data.datetime[0]
if self._market_data is None:
self._market_data = event.market_data
else:
self._market_data = self._market_data + event.market_data
self.on_bar(event)
if event.callback:
event.callback(event) |
同步账户
Arguments:
sync_message {[type]} -- [description]
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)
self.history = []
self.cash = [self.init_cash]
self.cash_available = self.cash[-1] |
外部操作|高危|
def change_cash(self, money):
"""
外部操作|高危|
"""
res = self.cash[-1] + money
if res >= 0:
# 高危操作
self.cash[-1] = res |
返回历史成交
Arguments:
start {str} -- [description]
end {str]} -- [description]
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),
pd.Timestamp(end))] |
存储order_handler的order_status
Arguments:
orderlist {[dataframe]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
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.order
collection.create_index(
[('account_cookie',
ASCENDING),
('realorder_id',
ASCENDING)],
unique=True
)
try:
orderlist = QA_util_to_json_from_pandas(orderlist.reset_index())
for item in orderlist:
if item:
#item['date']= QA_util_get_order_day()
collection.update_one(
{
'account_cookie': item.get('account_cookie'),
'realorder_id': item.get('realorder_id')
},
{'$set': item},
upsert=True
)
except Exception as e:
print(e)
pass |
存储order_handler的deal_status
Arguments:
dealist {[dataframe]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
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
collection.create_index(
[('account_cookie',
ASCENDING),
('trade_id',
ASCENDING)],
unique=True
)
try:
dealist = QA_util_to_json_from_pandas(dealist.reset_index())
collection.insert_many(dealist, ordered=False)
except Exception as e:
pass |
增量存储order_queue
Arguments:
order_queue {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
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(
[('account_cookie',
ASCENDING),
('order_id',
ASCENDING)],
unique=True
)
for order in order_queue.values():
order_json = order.to_dict()
try:
collection.update_one(
{
'account_cookie': order_json.get('account_cookie'),
'order_id': order_json.get('order_id')
},
{'$set': order_json},
upsert=True
)
except Exception as e:
print(e) |
威廉SMA算法
本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index
2018/5/3
@yutiansut
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.iloc[i] # Y'
ret.append(preY)
while i < length:
Y = (M * Series.iloc[i] + (N - M) * preY) / float(N)
ret.append(Y)
preY = Y
i += 1
return pd.Series(ret, index=Series.tail(len(ret)).index) |
A<B then A>B A上穿B B下穿A
Arguments:
A {[type]} -- [description]
B {[type]} -- [description]
Returns:
[type] -- [description]
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) |
2018/05/23 修改
参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429
现在返回的是series
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() |
表达持续性
从前N1日到前N2日一直满足COND条件
Arguments:
COND {[type]} -- [description]
N1 {[type]} -- [description]
N2 {[type]} -- [description]
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() |
平均绝对偏差 mean absolute deviation
修正: 2018-05-25
之前用mad的计算模式依然返回的是单值
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) |
macd指标 仅适用于Series
对于DATAFRAME的应用请使用QA_indicator_macd
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.DataFrame(DICT)
return VAR |
多空指标
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 |
支持MultiIndex的cond和DateTimeIndex的cond
条件成立 yes= True 或者 yes=1 根据不同的指标自己定
Arguments:
cond {[type]} -- [description]
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
elif isinstance(cond.index, pd.DatetimeIndex):
return len(cond)-cond.index.tolist().index(cond[cond != yes].index[-1])-1 |
today all
Returns:
[type] -- [description]
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_stock_day(
code, today, today, '00', ip=bestip)
except:
bestip = select_best_ip()['stock']
l = QA_fetch_get_stock_day(
code, today, today, '00', ip=bestip)
if l is not None:
data.append(l)
res = pd.concat(data)
if output in ['pd']:
return res
elif output in ['QAD']:
return QA_DataStruct_Stock_day(res.set_index(['date', 'code'], drop=False)) |
save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用
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()
coll_stock_day = client.stock_day
coll_stock_day.create_index(
[("code",
pymongo.ASCENDING),
("date_stamp",
pymongo.ASCENDING)]
)
err = []
# saveing result
def __gen_param(stock_list, coll_stock_day, ip_list=[]):
results = []
count = len(ip_list)
total = len(stock_list)
for item in range(len(stock_list)):
try:
code = stock_list[item]
QA_util_log_info(
'##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)),
ui_log
)
# 首选查找数据库 是否 有 这个代码的数据
search_cond = {'code': str(code)[0:6]}
ref = coll_stock_day.find(search_cond)
end_date = str(now_time())[0:10]
ref_count = coll_stock_day.count_documents(search_cond)
# 当前数据库已经包含了这个代码的数据, 继续增量更新
# 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现
if ref_count > 0:
# 接着上次获取的日期继续更新
start_date = ref[ref_count - 1]['date']
# print("ref[ref.count() - 1]['date'] {} {}".format(ref.count(), coll_stock_day.count_documents({'code': str(code)[0:6]})))
else:
# 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据
start_date = '1990-01-01'
QA_util_log_info(
'UPDATE_STOCK_DAY \n Trying updating {} from {} to {}'
.format(code,
start_date,
end_date),
ui_log
)
if start_date != end_date:
# 更新过的,不更新
results.extend([(code, start_date, end_date, '00', 'day', ip_list[item % count]['ip'],
ip_list[item % count]['port'], item, total, ui_log, ui_progress)])
except Exception as error0:
print('Exception:{}'.format(error0))
err.append(code)
return results
ips = get_ip_list_by_multi_process_ping(stock_ip_list, _type='stock')[:cpu_count() * 2 + 1]
param = __gen_param(stock_list, coll_stock_day, ips)
ps = QA_SU_save_stock_day_parallelism(processes=cpu_count() if len(ips) >= cpu_count() else len(ips),
client=client, ui_log=ui_log)
ps.add(do_saving_work, param)
ps.run()
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) |
用户登陆
不使用 QAUSER库
只返回 TRUE/FALSE
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 False
else:
return True |
只做check! 具体逻辑需要在自己的函数中实现
参见:QAWEBSERVER中的实现
Arguments:
name {[type]} -- [description]
password {[type]} -- [description]
client {[type]} -- [description]
Returns:
[type] -- [description]
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.user
if (coll.find({'username': name}).count() > 0):
print(name)
QA_util_log_info('user name is already exist')
return False
else:
return True |
对order/market的封装
[description]
Arguments:
order {[type]} -- [description]
Returns:
[type] -- [description]
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 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 |
get_filename
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')]] |
会创建一个download/文件夹
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(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 |
读取历史财务数据文件,并返回pandas结果 , 类似gpcw20171231.zip格式,具体字段含义参考
https://github.com/rainx/pytdx/issues/133
:param data_file: 数据文件地址, 数据文件类型可以为 .zip 文件,也可以为解压后的 .dat
:return: pandas DataFrame格式的历史财务数据
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 = QAHistoryFinancialCrawler()
with open(data_file, 'rb') as df:
data = crawler.parse(download_file=df)
return crawler.to_df(data) |
return shanghai margin data
Arguments:
date {str YYYY-MM-DD} -- date format
Returns:
pandas.DataFrame -- res for margin data
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
(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 shenzhen margin data
Arguments:
date {str YYYY-MM-DD} -- date format
Returns:
pandas.DataFrame -- res for margin data
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') |
更新市场数据
broker 为名字,
data 是市场数据
被 QABacktest 中run 方法调用 upcoming_data
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
)) |
开启查询子线程(实盘中用)
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() |
login 登录到交易前置
2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态
Arguments:
broker_name {[type]} -- [description]
account_cookie {[type]} -- [description]
Keyword Arguments:
account {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
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]} -- [description] (default: {None})
Returns:
[type] -- [description]
"""
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 |
同步账户信息
Arguments:
broker_id {[type]} -- [description]
account_cookie {[type]} -- [description]
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
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 |
内部函数
def _trade(self, event):
"内部函数"
print('==================================market enging: trade')
print(self.order_handler.order_queue.pending)
print('==================================')
self.order_handler._trade()
print('done') |
交易前置结算
1. 回测: 交易队列清空,待交易队列标记SETTLE
2. 账户每日结算
3. broker结算更新
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=self.trade_engine.kernels_dict['ORDER'].queue
)
) |
需要对于datetime 和date 进行转换, 以免直接被变成了时间戳
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')) |
将所有沪深股票从数字转化到6位的代码
因为有时候在csv等转换的时候,诸如 000001的股票会变成office强制转化成数字1
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'
# 天软股票代码格式 '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]) |
转换code==> list
Arguments:
code {[type]} -- [description]
Keyword Arguments:
auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True})
Returns:
[list] -- [description]
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):
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] |
订阅一个策略
会扣减你的积分
Arguments:
strategy_id {str} -- [description]
last {int} -- [description]
Keyword Arguments:
today {[type]} -- [description] (default: {datetime.date.today()})
cost_coins {int} -- [description] (default: {10})
def subscribe_strategy(
self,
strategy_id: str,
last: int,
today=datetime.date.today(),
cost_coins=10
):
"""订阅一个策略
会扣减你的积分
Arguments:
strategy_id {str} -- [description]
last {int} -- [description]
Keyword Arguments:
today {[type]} -- [description] (default: {datetime.date.today()})
cost_coins {int} -- [description] (default: {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' |
取消订阅某一个策略
Arguments:
strategy_id {[type]} -- [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[strategy_id]['status'] = 'canceled'
self.coins_history.append(
[0,
strategy_id,
str(today),
0,
order_id,
'unsubscribe']
) |
订阅一个策略
Returns:
[type] -- [description]
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())
)
)
#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"') |
根据 self.user_cookie 创建一个 portfolio
:return:
如果存在 返回 新建的 QA_Portfolio
如果已经存在 返回 这个portfolio
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] |
直接从二级目录拿到account
Arguments:
portfolio_cookie {str} -- [description]
account_cookie {str} -- [description]
Returns:
[type] -- [description]
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.portfolio_list[portfolio_cookie][account_cookie]
except:
return None |
make a simple account with a easier way
如果当前user中没有创建portfolio, 则创建一个portfolio,并用此portfolio创建一个account
如果已有一个或多个portfolio,则使用第一个portfolio来创建一个account
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()
else:
po = list(self.portfolio_list.values())[0]
ac = po.new_account()
return ac, po |
注册一个account到portfolio组合中
account 也可以是一个策略类,实现其 on_bar 方法
:param account: 被注册的account
:return:
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) |
将QA_USER的信息存入数据库
ATTENTION:
在save user的时候, 需要同时调用 user/portfolio/account链条上所有的实例化类 同时save
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},
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() |
基于账户/密码去sync数据库
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.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 |
恢复方法
Arguments:
message {[type]} -- [description]
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 = 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 = {} |
对输入日期进行格式化处理,返回格式为 "%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-03-02"
:param cursor_date: str/datetime.datetime/int 日期或时间
:return: str 返回字符串格式日期
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-03-02"
:param cursor_date: str/datetime.datetime/int 日期或时间
:return: str 返回字符串格式日期
"""
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 个交易日 (不包含当前交易日)
:param date:
:param n:
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 = QA_util_get_real_date(cursor_date)
return QA_util_date_gap(real_pre_trade_date, n, "gt") |
得到前 n 个交易日 (不包含当前交易日)
:param date:
:param n:
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(cursor_date)
return QA_util_date_gap(real_aft_trade_date, n, "lt") |
时间是否交易
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 |
获取真实的交易日期,其中,第三个参数towards是表示向前/向后推
towards=1 日期向后迭代
towards=-1 日期向前迭代
@ yutiansut
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(
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] |
取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist
@yutiansut
2017/8/10
当start end中间没有交易日 返回None, None
@yutiansut/ 2017-12-19
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_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) |
给出交易具体时间
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 |
返回start_day到end_day中间有多少个交易天 算首尾
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 |
:param date: 字符串起始日 类型 str eg: 2018-11-11
:param gap: 整数 间隔多数个交易日
:param methods: gt大于 ,gte 大于等于, 小于lt ,小于等于lte , 等于===
:return: 字符串 eg:2000-01-01
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' |
交易的真实日期
Returns:
[type] -- [description]
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_date(str(dt.date()), trade_date_sse, 1) |
委托的真实日期
Returns:
[type] -- [description]
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)
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()
) |
输入是真实交易时间,返回按期货交易所规定的时间* 适用于tb/文华/博弈的转换
Arguments:
real_datetime {[type]} -- [description]
Returns:
[type] -- [description]
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_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) |
输入是交易所规定的时间,返回真实时间*适用于通达信的时间转换
Arguments:
trade_datetime {[type]} -- [description]
Returns:
[type] -- [description]
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)[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) |
创建股票的小时线的index
Arguments:
day {[type]} -- [description]
Returns:
[type] -- [description]
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',
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']) |
分钟线回测的时候的gap
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 |
QA_util_save_csv(data,name,column,location)
将list保存成csv
第一个参数是list
第二个参数是要保存的名字
第三个参数是行的名称(可选)
第四个是保存位置(可选)
@yutiansut
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 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]) |
查询现金和持仓
Arguments:
accounts {[type]} -- [description]
Returns:
dict-- {'cash_available':xxx,'hold_available':xxx}
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 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 |
查询clients
Returns:
[type] -- [description]
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',
'processId'],
axis=1
)
else:
return pd.DataFrame(
None,
columns=[
'id',
'name',
'windowsTitle',
'accountInfo',
'status'
]
)
except Exception as e:
return False, e |
查询订单
Arguments:
accounts {[type]} -- [description]
Keyword Arguments:
status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})
Returns:
[type] -- [description]
def query_orders(self, accounts, status='filled'):
"""查询订单
Arguments:
accounts {[type]} -- [description]
Keyword Arguments:
status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})
Returns:
[type] -- [description]
"""
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 |
[summary]
Arguments:
accounts {[type]} -- [description]
code {[type]} -- [description]
price {[type]} -- [description]
amount {[type]} -- [description]
Keyword Arguments:
order_direction {[type]} -- [description] (default: {ORDER_DIRECTION.BUY})
order_model {[type]} -- [description] (default: {ORDER_MODEL.LIMIT})
priceType 可选择: 上海交易所:
0 - 限价委托
4 - 五档即时成交剩余撤销
6 - 五档即时成交剩余转限
深圳交易所:
0 - 限价委托
1 - 对手方最优价格委托
2 - 本方最优价格委托
3 - 即时成交剩余撤销委托
4 - 五档即时成交剩余撤销
5 - 全额成交或撤销委托
Returns:
[type] -- [description]
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]
code {[type]} -- [description]
price {[type]} -- [description]
amount {[type]} -- [description]
Keyword Arguments:
order_direction {[type]} -- [description] (default: {ORDER_DIRECTION.BUY})
order_model {[type]} -- [description] (default: {ORDER_MODEL.LIMIT})
priceType 可选择: 上海交易所:
0 - 限价委托
4 - 五档即时成交剩余撤销
6 - 五档即时成交剩余转限
深圳交易所:
0 - 限价委托
1 - 对手方最优价格委托
2 - 本方最优价格委托
3 - 即时成交剩余撤销委托
4 - 五档即时成交剩余撤销
5 - 全额成交或撤销委托
Returns:
[type] -- [description]
"""
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 |
获取某一时间的某一只股票的指标
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') |
获取已经被终止上市的股票列表,数据从上交所获取,目前只有在上海证券交易所交易被终止的股票。
collection:
code:股票代码 name:股票名称 oDate:上市日期 tDate:终止上市日期
:param client:
:return: None
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") |
获取 股票的 基本信息,包含股票的如下信息
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:
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") |
save stock_day
保存日线数据
:param client:
:param ui_log: 给GUI qt 界面使用
:param ui_progress: 给GUI qt 界面使用
:param ui_progress_int_value: 给GUI qt 界面使用
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) |
输入一个dict 返回删除后的
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 dicts |
异步mongo示例
Keyword Arguments:
uri {str} -- [description] (default: {'mongodb://localhost:27017/quantaxis'})
Returns:
[type] -- [description]
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_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) |
portfolio add a account/stratetgy
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 |
删除一个account
Arguments:
account_cookie {[type]} -- [description]
Raises:
RuntimeError -- [description]
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)
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
Keyword Arguments:
account_cookie {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
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})
Returns:
[type] -- [description]
"""
if account_cookie is None:
"""创建新的account
Returns:
[type] -- [description]
"""
# 如果组合的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) |
'give the account_cookie and return the account/strategy back'
:param cookie:
:return: QA_Account with cookie if in dict
None not in list
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 |
check the account whether in the protfolio dict or not
:param account: QA_Account
:return: QA_Account if in dict
None not in list
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 |
portfolio 的cookie
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,
'history': self.history
} |
基于portfolio对子账户下单
Arguments:
account_cookie {str} -- [description]
Keyword Arguments:
code {[type]} -- [description] (default: {None})
amount {[type]} -- [description] (default: {None})
time {[type]} -- [description] (default: {None})
towards {[type]} -- [description] (default: {None})
price {[type]} -- [description] (default: {None})
money {[type]} -- [description] (default: {None})
order_model {[type]} -- [description] (default: {None})
amount_model {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
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
):
"""基于portfolio对子账户下单
Arguments:
account_cookie {str} -- [description]
Keyword Arguments:
code {[type]} -- [description] (default: {None})
amount {[type]} -- [description] (default: {None})
time {[type]} -- [description] (default: {None})
towards {[type]} -- [description] (default: {None})
price {[type]} -- [description] (default: {None})
money {[type]} -- [description] (default: {None})
order_model {[type]} -- [description] (default: {None})
amount_model {[type]} -- [description] (default: {None})
Returns:
[type] -- [description]
"""
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
) |
存储过程
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.