/
QAAccountPro.py
executable file
·1923 lines (1649 loc) · 67.9 KB
/
QAAccountPro.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2019 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import copy
import datetime
import warnings
import numpy as np
import pandas as pd
from pymongo import DESCENDING, ASCENDING
from QUANTAXIS import __version__
from QUANTAXIS.QAARP.market_preset import MARKET_PRESET
from QUANTAXIS.QAEngine.QAEvent import QA_Worker
from QUANTAXIS.QAMarket.QAOrder import QA_Order, QA_OrderQueue
from QUANTAXIS.QAMarket.QAPosition import QA_Position, QA_PMS
from QUANTAXIS.QASU.save_account import save_account, update_account
from QUANTAXIS.QAUtil.QASetting import DATABASE
from QUANTAXIS.QAUtil.QADate_trade import (
QA_util_get_next_day,
QA_util_get_trade_range
)
from QUANTAXIS.QAUtil.QAParameter import (
ACCOUNT_EVENT,
AMOUNT_MODEL,
BROKER_TYPE,
ENGINE_EVENT,
FREQUENCE,
MARKET_TYPE,
ORDER_DIRECTION,
ORDER_MODEL,
RUNNING_ENVIRONMENT,
TRADE_STATUS,
EXCHANGE_ID
)
from QUANTAXIS.QAUtil.QARandom import QA_util_random_with_topic
# pylint: disable=old-style-class, too-few-public-methods
class QA_AccountPRO(QA_Worker):
"""QA_Account
QAAccount
在QAAccountPro/Position的模型中, Pos不负责OMS业务,因此, 需要使用AccPro的sendOrder来主导OMS模型
一个简单的外部OMS
POS 下单以后, 订单信息被AccPro接受, 并生成QA_Order
基于QA_Order的成交 ==> receive_deal的回报模式, 记录history 更新POS的on_transaction
"""
def __init__(
self,
user_cookie: str,
portfolio_cookie: str,
account_cookie=None,
strategy_name=None,
market_type=MARKET_TYPE.STOCK_CN,
frequence=FREQUENCE.DAY,
broker=BROKER_TYPE.BACKETEST,
init_hold={},
init_cash=1000000,
commission_coeff=0.00025,
tax_coeff=0.001,
margin_level={},
allow_t0=False,
allow_sellopen=False,
allow_margin=False,
running_environment=RUNNING_ENVIRONMENT.BACKETEST,
auto_reload=False,
generated='direct',
start=None,
end=None
):
"""
:param [str] strategy_name: 策略名称
:param [str] user_cookie: 用户cookie
:param [str] portfolio_cookie: 组合cookie
:param [str] account_cookie: 账户cookie
:param [dict] init_hold 初始化时的股票资产
:param [float] init_cash: 初始化资金
:param [float] commission_coeff: 交易佣金 :默认 万2.5 float 类型
:param [float] tax_coeff: 印花税 :默认 千1.5 float 类型
:param [Bool] margin_level: 保证金比例 默认{}
:param [Bool] allow_t0: 是否允许t+0交易 默认False
:param [Bool] allow_sellopen: 是否允许卖空开仓 默认False
:param [Bool] allow_margin: 是否允许保证金交易 默认False
:param [Bool] auto_reload: 是否自动从数据库中同步数据
:param [Bool] generated: 从哪里生成==> directed: 直接生成 portfolio: 组合生成
### 注意
>>>>>>>>>>>>>
在期货账户中:
allow_t0/ allow_sellopen 是必须打开的
allow_margin 是作为保证金账户的开关 默认关闭 可以打开 则按照market_preset中的保证金比例来计算
具体可以参见: https://github.com/QUANTAXIS/QUANTAXIS/blob/master/EXAMPLE/test_backtest/FUTURE/TEST_%E4%BF%9D%E8%AF%81%E9%87%91%E8%B4%A6%E6%88%B7.ipynb
>>>>>>>>>>>>>
:param [QA.PARAM] market_type: 市场类别 默认QA.MARKET_TYPE.STOCK_CN A股股票
:param [QA.PARAM] frequence: 账户级别 默认日线QA.FREQUENCE.DAY
:param [QA.PARAM] broker: BROEKR类 默认回测 QA.BROKER_TYPE.BACKTEST
:param [QA.PARAM] running_environment 当前运行环境 默认Backtest
# 2018/06/11 init_assets 从float变为dict,并且不作为输入,作为只读属性
# :param [float] init_assets: 初始资产 默认 1000000 元 (100万)
init_assets:{
cash: xxx,
stock: {'000001':2000},
init_date: '2018-02-05',
init_datetime: '2018-02-05 15:00:00'
}
# 2018/06/11 取消在初始化的时候的cash和history输入
# :param [list] cash: 可用现金 默认 是 初始资产 list 类型
# :param [list] history: 交易历史
# 2018/11/9 修改保证金交易
# 我们把冻结的保证金 看做是未来的已实现交易:
# 如==> 当前的一手空单 认为是未来的卖出成交(已知价格 不知时间)
# 因此我们如此对于保证金交易进行评估:
# 账户买入:
多单开仓: cash 下降x 保证金增加x 增加一手未来的卖出合约(持仓) ==> 平仓: cash上升 保证金恢复
cash + frozen(平仓释放) + 未平仓位
cash, available_cash
frozen{
RB1901: {
towards 2: {avg_money : xxx, amount: xxx, queue: collection.deque()},
towards -2: {avg_money, amount, queue: collection.deque()}
},
IF1901: {
towards 2: {avg_money, amount,queue: collection.deque()},
towards -2: {avg_money, amount,queue: collection.deque()}
}
}
}
hold: {
RB1901: {
1, amount, # 多单待平仓
-1, amount # 空单待平仓
}
}
>>>>>>>>>>>>>>>>>>>>>>>>>
init_hold面临的一个改进和问题:
>> init_hold就是简化的position模型
init_hold目前是一个类似这样的字段:
{'000001':100}
实际上我们需要对于他进行进一步的改进, 用以用于支持更多场景:
{
'code': 000001, #品种名称
'instrument_id': 000001,
'name': '中国平安', #
'market_type': QA.MARKET_TYPE.STOCK_CN,
'exchange_id': QA.EXCHANGE_ID.SZSE, #交易所ID
'volume_short': 0, #空头持仓数量
'volume_long': 100, #持仓数量
'volume_long_today': 0,
'volume_long_his': 1,
'volume_long': 1,
'volume_long_frozen_today': 0,
'volume_long_frozen_his': 0,
'volume_long_frozen': 0,
'volume_short_today': 0,
'volume_short_his: 0,
'volume_short': 0,
'volume_short_frozen_today': 0,
'volume_short_frozen_his': 0,
'volume_short_frozen': 0,
'position_price_long': 9.5, #多头成本价
'position_cost_long': 9500, # 多头成本
'position_price_short': 0,
'position_cost_short': 0,
'open_price_long': 9.5, #多头开仓价
'open_cost_long': 9500, #多头开仓成本
'open_price_short': 0, #空头开仓价
'open_cost_short': 0, #空头成本
'margin_long': 0, # 多头保证金
'margin_short': 0,
'margin': 0
}
AccPro 使用QA_Position来创建仓位管理
- 当创建QA_Account的时候, 会从Positions库中查询并恢复新的Positions
- 当申请创建一个新的分区的时候,Account会扣减一个额度(money_preset) 体现在cash/history中
- 当删除一个poistion 释放额度
- 策略会写入相应的position分区
| AccPro |
| MPMS | MPMS | SPMS | FREECASH |
| POS POS | POS POS POS | POS | |
"""
super().__init__()
# warnings.warn('QUANTAXIS 1.0.46 has changed the init_assets ==> init_cash, please pay attention to this change if you using init_cash to initial an account class,\
# ', DeprecationWarning, stacklevel=2)
self._history_headers = [
'datetime', # 日期/时间
'code', # 品种
'price', # 成交价
'amount', # 成交数量(股票 股数 期货 手数)
'cash', # 现金
'order_id', # 本地订单号
'realorder_id', # 实际委托单号
'trade_id', # 成交单号
'account_cookie', # 账号id
'commission', # 手续费
'tax', # 税
'message', # 备注
'frozen', # 冻结资金.
'direction' # 方向
]
self._activity_headers = [
'datetime',
'activity',
'event',
''
]
self.activity = []
########################################################################
# 信息类:
if user_cookie is None or portfolio_cookie is None:
raise RuntimeError('QUANTAXIS 1.3.0升级: 需要在创建Account的时候指定用户名/组合名')
self.user_cookie = user_cookie
self.strategy_name = strategy_name
self.portfolio_cookie = portfolio_cookie
self.account_cookie = QA_util_random_with_topic(
'Acc'
) if account_cookie is None else account_cookie
self.market_type = market_type
self.broker = broker
self.frequence = frequence
self.running_environment = running_environment
########################################################################
self._market_data = None
self._currenttime = None
self.commission_coeff = commission_coeff
self.tax_coeff = tax_coeff
self.datetime = None
self.running_time = datetime.datetime.now()
self.quantaxis_version = __version__
self.client = DATABASE.accountPro
self.start_ = start
self.end_ = end
### 下面是数据库创建index部分, 此部分可能导致部分代码和原先不兼容
self.client.create_index(
[
("account_cookie",
ASCENDING),
("user_cookie",
ASCENDING),
("portfolio_cookie",
ASCENDING)
],
unique=True
)
########################################################################
# 资产类
self.orders = QA_OrderQueue() # 历史委托单
self.PMS = QA_PMS()
# self.risks = QA_RMS()
self.init_cash = init_cash
self.init_hold = pd.Series(
init_hold,
name='amount'
) if isinstance(init_hold,
dict) else init_hold
self.init_hold.index.name = 'code'
self.cash = [self.init_cash]
self.cash_available = self.cash[-1] # 可用资金
self.sell_available = copy.deepcopy(self.init_hold)
self.buy_available = copy.deepcopy(self.init_hold)
self.history = []
self.time_index_max = []
# 在回测中, 每日结算后更新
# 真实交易中, 为每日初始化/每次重新登录后的同步信息
self.static_balance = {
'static_assets': [],
'cash': [],
'frozen': [],
'hold': [],
'date': []
} # 日结算
self.today_trade = {'last': [], 'current': []}
self.today_orders = {'last': [], 'current': []}
self.pms = {}
self.allow_t0 = allow_t0
self.allow_sellopen = allow_sellopen
self.allow_margin = allow_margin
self.margin_level = margin_level # 保证金比例
if self.market_type is MARKET_TYPE.FUTURE_CN:
self.allow_t0 = True
self.allow_sellopen = True
self.allow_margin = True
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
对应平仓的时候, 释放保证金
1. frozen 是一个dict : {[code]:queue}
key是标的 value是对应的交易queue
"""
self.frozen = {} # 冻结资金(保证金)
self.finishedOrderid = []
if auto_reload:
self.reload()
def __repr__(self):
return '< QA_AccountPRO {} market: {}>'.format(
self.account_cookie,
self.market_type
)
@property
def message(self):
'the standard message which can be transfer'
return {
'source':
'account',
'frequence':
self.frequence,
'account_cookie':
self.account_cookie,
'portfolio_cookie':
self.portfolio_cookie,
'user_cookie':
self.user_cookie,
'broker':
self.broker,
'market_type':
self.market_type,
'strategy_name':
self.strategy_name,
'current_time':
str(self._currenttime),
'allow_sellopen':
self.allow_sellopen,
'allow_margin':
self.allow_margin,
'allow_t0':
self.allow_t0,
'margin_level':
self.margin_level,
'init_assets':
self.init_assets,
'init_cash':
self.init_cash,
'init_hold':
self.init_hold.to_dict(),
'commission_coeff':
self.commission_coeff,
'tax_coeff':
self.tax_coeff,
'cash':
self.cash,
'history':
self.history,
'trade_index':
self.time_index_max,
'running_time':
str(datetime.datetime.now())
if self.running_time is None else str(self.running_time),
'quantaxis_version':
self.quantaxis_version,
'running_environment':
self.running_environment,
'start_date':
self.start_date,
'end_date':
self.end_date,
'frozen':
self.frozen,
'finished_id':
self.finishedOrderid,
'position_id':
list(self.pms.keys())
}
@property
def freecash_precent(self):
"""剩余资金比例
Returns:
float
"""
return self.cash_available / self.init_cash
def load_marketpreset(self):
"""加载市场表
"""
self.market_preset = MARKET_PRESET()
@property
def init_hold_with_account(self):
"""带account_cookie的初始化持仓
Returns:
[type] -- [description]
"""
return self.init_hold.reset_index().assign(
account_cookie=self.account_cookie
).set_index(['code',
'account_cookie'])
@property
def init_assets(self):
"""初始化账户资产
Returns:
dict -- 2keys-cash,hold
"""
return {'cash': self.init_cash, 'hold': self.init_hold.to_dict()}
@property
def code(self):
"""
该账户曾交易代码 用set 去重
"""
return list(set([item[1] for item in self.history]))
@property
def date(self):
"""账户运行的日期
Arguments:
self {[type]} -- [description]
Returns:
[type] -- [description]
"""
if self.datetime is not None:
return str(self.datetime)[0:10]
else:
return None
@property
def positions(self):
raise NotImplementedError
@property
def start_date(self):
"""账户的起始交易日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description]
"""
if self.start_ == None:
if len(self.time_index_max) > 0:
return str(min(self.time_index_max))[0:10]
else:
print(
RuntimeWarning(
'QAACCOUNT: THIS ACCOUNT DOESNOT HAVE ANY TRADE'
)
)
else:
return self.start_
@property
def end_date(self):
"""账户的交易结束日期(只在回测中使用)
Raises:
RuntimeWarning -- [description]
Returns:
[type] -- [description]
"""
if self.start_ == None:
if len(self.time_index_max) > 0:
return str(max(self.time_index_max))[0:10]
else:
print(
RuntimeWarning(
'QAACCOUNT: THIS ACCOUNT DOESNOT HAVE ANY TRADE'
)
)
else:
return self.end_
@property
def market_data(self):
return self._market_data
@property
def trade_range(self):
return QA_util_get_trade_range(self.start_date, self.end_date)
@property
def trade_range_max(self):
if self.start_date < str(min(self.time_index_max))[0:10]:
return QA_util_get_trade_range(self.start_date, self.end_date)
else:
return QA_util_get_trade_range(str(min(self.time_index_max))[0:10], str(max(self.time_index_max))[0:10])
@property
def time_index(self):
if len(self.time_index_max):
res_ = pd.DataFrame(self.time_index_max)
res_.columns = (['datetime'])
res_['date'] = [i[0:10] for i in res_['datetime']]
res_ = res_[res_['date'].isin(self.trade_range)]
return list(res_['datetime'])
else:
return self.time_index_max
@property
def history_min(self):
if len(self.history):
res_ = pd.DataFrame(self.history)
res_['date'] = [i[0:10] for i in res_[0]]
res_ = res_[res_['date'].isin(self.trade_range)]
return np.array(res_.drop(['date'], axis=1)).tolist()
else:
return self.history
@property
def history_table_min(self):
'区间交易历史的table'
if len(self.history_min) > 0:
lens = len(self.history_min[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history_min,
columns=self._history_headers[:lens]
).sort_index()
@property
def trade_day(self):
return list(
pd.Series(self.time_index_max).apply(
lambda x: str(x)[0:10]).unique()
)
@property
def history_table(self):
'交易历史的table'
if len(self.history) > 0:
lens = len(self.history[0])
else:
lens = len(self._history_headers)
return pd.DataFrame(
data=self.history,
columns=self._history_headers[:lens]
).sort_index()
@property
def today_trade_table(self):
return pd.DataFrame(
data=self.today_trade['current'],
columns=self._history_headers
).sort_index()
@property
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 create_position(self, code, money_preset):
if self.cash_available > money_preset:
pos = QA_Position(code=code, money_preset=money_preset, user_cookie=self.user_cookie,
portfolio_cookie=self.portfolio_cookie, account_cookie=self.account_cookie, auto_reload=True)
self.pms[pos.position_id] = pos
self.cash.append(self.cash[-1] - money_preset)
self.cash_available = self.cash[-1]
return pos
else:
return False
def get_position(self, position_id):
return self.pms.get(position_id, None)
@property
def hold(self):
"""真实持仓
"""
return pd.concat(
[self.init_hold,
self.hold_available]
).groupby('code').sum().replace(0,
np.nan).dropna().sort_index()
@property
def hold_available(self):
"""可用持仓
"""
return self.history_table.groupby('code').amount.sum().replace(
0,
np.nan
).dropna().sort_index()
# @property
# def order_table(self):
# """return order trade list"""
# return self.orders.trade_list
@property
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()
@property
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_
@property
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_
@property
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_
@property
def latest_cash(self):
'return the lastest cash 可用资金'
return self.cash[-1]
@property
def current_time(self):
'return current time (in backtest/real environment)'
return self._currenttime
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()
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()
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()
# @property
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()
def reset_assets(self, init_cash=None):
'reset_history/cash/'
self.sell_available = copy.deepcopy(self.init_hold)
self.history = []
self.init_cash = init_cash
self.cash = [self.init_cash]
self.cash_available = self.cash[-1] # 在途资金
def receive_simpledeal(
self,
code,
trade_price,
trade_amount,
trade_towards,
trade_time,
message=None,
order_id=None,
trade_id=None,
realorder_id=None
):
"""快速撮合成交接口
此接口是一个直接可以成交的接口, 所以务必确保给出的信息是可以成交的
此接口涉及的是
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: 目前还不支持期货的锁仓