Skip to content

Commit

Permalink
update risk/frozen and many more
Browse files Browse the repository at this point in the history
update risk/frozen and many more
  • Loading branch information
yutiansut authored Mar 1, 2019
2 parents 66e29ce + 99ad643 commit 661579d
Show file tree
Hide file tree
Showing 10 changed files with 811 additions and 57 deletions.

Large diffs are not rendered by default.

File renamed without changes.
File renamed without changes.
96 changes: 54 additions & 42 deletions QUANTAXIS/QAARP/QAAccount.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,8 +333,9 @@ def __init__(
self.allow_t0 = True
self.allow_sellopen = True

if self.allow_t0 and self.allow_sellopen or self.market_type is MARKET_TYPE.FUTURE_CN:
self.load_marketpreset()
self.market_preset = MARKET_PRESET()
# if self.allow_t0 and self.allow_sellopen or self.market_type is MARKET_TYPE.FUTURE_CN:
# self.load_marketpreset()
"""期货的多开/空开 ==> 资金冻结进保证金 frozen
对应平仓的时候, 释放保证金
Expand Down Expand Up @@ -379,6 +380,8 @@ def message(self):
str(self._currenttime),
'allow_sellopen':
self.allow_sellopen,
'allow_margin':
self.allow_margin,
'allow_t0':
self.allow_t0,
'margin_level':
Expand Down Expand Up @@ -409,7 +412,9 @@ def message(self):
'start_date':
self.start_date,
'end_date':
self.end_date
self.end_date,
'frozen':
self.frozen
}

@property
Expand Down Expand Up @@ -602,14 +607,6 @@ def hold(self):
).groupby('code').sum().replace(0,
np.nan).dropna().sort_index()

# @property
# def hold_available_temp(self):
# """可用持仓
# """
# return self._table.groupby('code').amount.sum().replace(
# 0,
# np.nan
# ).dropna().sort_index()

@property
def hold_available(self):
Expand Down Expand Up @@ -670,8 +667,11 @@ def daily_hold(self):
return pd.concat([res.reset_index().set_index('date'), pd.Series(data=None, index=pd.to_datetime(self.trade_range).set_names('date'), name='predrop')], axis=1)\
.ffill().drop(['predrop'], axis=1).reset_index().set_index(['date', 'account_cookie']).sort_index()

# 计算assets的时候 需要一个market_data=QA.QA_fetch_stock_day_adv(list(data.columns),data.index[0],data.index[-1])
# (market_data.to_qfq().pivot('close')*data).sum(axis=1)+user_cookie.get_account(a_1).daily_cash.set_index('date').cash

@property
def daily_frozen(self):
'每日交易结算时的持仓表'
return self.history_table.assign(date=pd.to_datetime(self.history_table.datetime)).set_index('date').resample('D').frozen.last()

@property
def latest_cash(self):
Expand Down Expand Up @@ -876,19 +876,19 @@ def receive_simpledeal(
if trade_towards in self.frozen[code].keys():
pass
else:
self.frozen[code][trade_towards] = {
self.frozen[code][str(trade_towards)] = {
'money': 0,
'amount': 0,
'avg_price': 0
}
else:
self.frozen[code] = {
ORDER_DIRECTION.BUY_OPEN: {
str(ORDER_DIRECTION.BUY_OPEN): {
'money': 0,
'amount': 0,
'avg_price': 0
},
ORDER_DIRECTION.SELL_OPEN: {
str(ORDER_DIRECTION.SELL_OPEN): {
'money': 0,
'amount': 0,
'avg_price': 0
Expand All @@ -903,73 +903,73 @@ def receive_simpledeal(
"""

self.frozen[code][trade_towards]['money'] = (
self.frozen[code][str(trade_towards)]['money'] = (
(
self.frozen[code][trade_towards]['money'] *
self.frozen[code][trade_towards]['amount']
self.frozen[code][str(trade_towards)]['money'] *
self.frozen[code][str(trade_towards)]['amount']
) + abs(trade_money)
) / (
self.frozen[code][trade_towards]['amount'] +
self.frozen[code][str(trade_towards)]['amount'] +
trade_amount
)
self.frozen[code][trade_towards]['avg_price'] = (
self.frozen[code][str(trade_towards)]['avg_price'] = (
(
self.frozen[code][trade_towards]['avg_price'] *
self.frozen[code][trade_towards]['amount']
self.frozen[code][str(trade_towards)]['avg_price'] *
self.frozen[code][str(trade_towards)]['amount']
) + abs(raw_trade_money)
) / (
self.frozen[code][trade_towards]['amount'] +
self.frozen[code][str(trade_towards)]['amount'] +
trade_amount
)
self.frozen[code][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.SELL_CLOSE]:
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 == ORDER_DIRECTION.BUY_CLOSE: # 买入平仓 之前是空开
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][ORDER_DIRECTION.SELL_OPEN
self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['amount'] -= trade_amount

frozen_part = self.frozen[code][
ORDER_DIRECTION.SELL_OPEN]['money'] * trade_amount
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][ORDER_DIRECTION.SELL_OPEN
if self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['amount'] == 0:
self.frozen[code][ORDER_DIRECTION.SELL_OPEN
self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['money'] = 0
self.frozen[code][ORDER_DIRECTION.SELL_OPEN
self.frozen[code][str(ORDER_DIRECTION.SELL_OPEN)
]['avg_price'] = 0

elif trade_towards == ORDER_DIRECTION.SELL_CLOSE: # 卖出平仓 之前是多开
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][ORDER_DIRECTION.BUY_OPEN
self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['amount'] -= trade_amount

frozen_part = self.frozen[code][ORDER_DIRECTION.BUY_OPEN
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][ORDER_DIRECTION.BUY_OPEN
if self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['amount'] == 0:
self.frozen[code][ORDER_DIRECTION.BUY_OPEN
self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['money'] = 0
self.frozen[code][ORDER_DIRECTION.BUY_OPEN
self.frozen[code][str(ORDER_DIRECTION.BUY_OPEN)
]['avg_price'] = 0
else: # 不允许卖空开仓的==> 股票

Expand Down Expand Up @@ -1007,7 +1007,8 @@ def receive_simpledeal(
)

else:
# print(self.cash[-1])
print('ALERT MONEY NOT ENOUGH!!!')
print(self.cash[-1])
self.cash_available = self.cash[-1]
#print('NOT ENOUGH MONEY FOR {}'.format(order_id))

Expand Down Expand Up @@ -1366,7 +1367,7 @@ def close_positions_order(self):
)
)

def settle(self):
def settle(self, settle_data = None):
"""
股票/期货的日结算
Expand All @@ -1375,8 +1376,16 @@ def settle(self):
期货的结算: 结转静态资金
"""
@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(
Expand All @@ -1385,6 +1394,7 @@ def settle(self):
)
)
if self.market_type == MARKET_TYPE.FUTURE_CN:
# 增加逐日盯市制度

self.static_balance['frozen'].append(
sum(
Expand Down Expand Up @@ -1489,6 +1499,7 @@ def from_message(self, message):
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
Expand All @@ -1510,6 +1521,7 @@ def from_message(self, message):
'running_environment',
RUNNING_ENVIRONMENT.BACKETEST
)
self.frozen = message.get('frozen', {})
self.settle()
return self

Expand Down
15 changes: 11 additions & 4 deletions QUANTAXIS/QAARP/QARisk.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,17 @@ def __init__(


if self.market_value is not None:
self._assets = (
self.market_value.sum(axis=1) +
self.account.daily_cash.set_index('date').cash
).fillna(method='pad')
if self.account.market_type == MARKET_TYPE.FUTURE_CN and self.account.allow_margin == True:
print('margin!')
self._assets = (
self.market_value.sum(axis=1) + self.account.daily_frozen.fillna(0) +
self.account.daily_cash.set_index('date').cash
).fillna(method='pad')
else:
self._assets = (
self.market_value.sum(axis=1) +
self.account.daily_cash.set_index('date').cash
).fillna(method='pad')
else:
self._assets = self.account.daily_cash.set_index('date'
).cash.fillna(
Expand Down
2 changes: 1 addition & 1 deletion QUANTAXIS/QAARP/market_preset.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def __init__(self):
'buy_frozen_coeff': 0.09,
'commission_coeff_peramount': 0.0001,
'commission_coeff_pervol': 0.0,
'commission_coeff_today_peramount': 5e-05,
'commission_coeff_today_peramount': 0.0001,
'commission_coeff_today_pervol': 0.0,
'exchange': 'SHFE',
'name': '螺纹钢',
Expand Down
1 change: 1 addition & 0 deletions QUANTAXIS/QAApplication/QABacktest.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ def run(self):
elif self.market_type in [MARKET_TYPE.FUND_CN,
MARKET_TYPE.INDEX_CN,
MARKET_TYPE.FUTURE_CN]:

self.market._settle(self.broker_name)

self.broker.run(
Expand Down
54 changes: 49 additions & 5 deletions QUANTAXIS/QAData/QADataStruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,6 @@ def __init__(self, DataFrame, dtype='stock_min', if_fq='bfq'):
except Exception as e:
raise e


self.type = dtype
self.if_fq = if_fq

Expand Down Expand Up @@ -322,6 +321,33 @@ def month(self):
def quarter(self):
return self.resample('Q')

@property
@lru_cache()
def tradedate(self):
"""返回交易所日历下的日期
Returns:
[type] -- [description]
"""

try:
return self.date
except:
return None

@property
@lru_cache()
def tradetime(self):
"""返回交易所日历下的日期
Returns:
[type] -- [description]
"""

try:
return self.date
except:
return None
# @property
# @lru_cache()
# def semiannual(self):
Expand Down Expand Up @@ -359,15 +385,29 @@ def choose_db(self):

@property
@lru_cache()
def trade_date(self):
def tradedate(self):
"""返回交易所日历下的日期
Returns:
[type] -- [description]
"""

try:
return self.data.trade_date
return self.data.tradetime.apply(lambda x: x[0:10])
except:
return None

@property
@lru_cache()
def tradetime(self):
"""返回交易所日历下的日期
Returns:
[type] -- [description]
"""

try:
return self.data.tradetime
except:
return None

Expand Down Expand Up @@ -772,9 +812,11 @@ def __init__(self, data, dtype='unknown_day', if_fq='bfq'):
class QA_DataStruct_Min(_quotation_base):
'''这个类是个通用类 一般不使用 特定生成的时候可能会用到 只具备基类方法
'''

def __init__(self, data, dtype='unknown_min', if_fq='bfq'):
super().__init__(data, dtype, if_fq)


class _realtime_base():
"""
realtime 基类
Expand Down Expand Up @@ -942,7 +984,7 @@ def _data(self):
@property
def datetime(self):
return self.index.levels[0]

@property
def code(self):
return self.index.levels[1]
Expand All @@ -951,15 +993,17 @@ def serialize(self):
"""to_protobuf
"""
pass

def to_json(self):
return self.data.assign(code=self.code, datetime=str(self.datetime)).to_dict(orient='records')

def resample(self, level):
return QA_data_tick_resample(self.data, level)


QA_DataStruct_Future_realtime = QA_DataStruct_Stock_realtime


class QA_DataStruct_Stock_realtime_series():
def __init__(self, sr_series):

Expand Down
Loading

0 comments on commit 661579d

Please sign in to comment.