Skip to content

Commit 393c5ce

Browse files
committed
修复股票回测bug
1 parent 6029476 commit 393c5ce

8 files changed

Lines changed: 167 additions & 68 deletions

File tree

‎quantdigger/demo/main.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from quantdigger.kernel.indicators.common import MA, BOLL
44
from quantdigger.kernel.engine.strategy import TradingStrategy
55
from quantdigger.util import pcontract, stock
6+
from quantdigger.kernel.datastruct import Direction
67
import plotting
78
#from quantdigger.kernel.engine.series import NumberSeries
89

@@ -42,13 +43,21 @@ def on_bar(self):
4243
try:
4344
begin_dt, end_dt = None, None
4445
pcon = pcontract('IF000.SHFE', '10.Minute')
45-
#pcon = stock('600848')
46+
#pcon = stock('600848') # 通过tushare下载股票数据
4647
simulator = ExecuteUnit([pcon, pcon], begin_dt, end_dt)
4748
algo = DemoStrategy(simulator)
4849
algo = DemoStrategy(simulator)
4950
#algo2 = DemoStrategy(simulator)
5051
simulator.run()
5152

53+
for deal in algo.blotter.deal_positions:
54+
# code...
55+
print "----------------"
56+
print("开仓时间: %s;成交价格: %f;买卖方向: %s;成交量: %d;盈亏: %f;") % \
57+
(deal.open_datetime, deal.open_price, Direction.type_to_str(deal.direction), deal.quantity, deal.profit())
58+
print("平仓时间: %s;成交价格: %f;买卖方向: %s;成交量: %d;盈亏: %f;") % \
59+
(deal.close_datetime, deal.close_price, Direction.type_to_str(deal.direction), deal.quantity, deal.profit())
60+
5261
# 显示回测结果
5362
plotting.plot_result(simulator.data[pcon],
5463
algo._indicators,

‎quantdigger/demo/plotting.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
matplotlib.use('TkAgg')
44
import matplotlib.pyplot as plt
55
from quantdigger.widgets.mplotwidgets import widgets, mplots
6-
from quantdigger.digger import statics
6+
from quantdigger.digger import finance
77

88
def plot_result(price_data, indicators, signals, blotter):
99
"""
1010
显示回测结果。
1111
"""
1212
try:
13-
curve = statics.create_equity_curve_dataframe(blotter.all_holdings)
14-
print statics.output_summary_stats(curve)
13+
curve = finance.create_equity_curve_dataframe(blotter.all_holdings)
14+
print finance.output_summary_stats(curve)
1515

1616
fig = plt.figure()
1717
frame = widgets.MultiWidgets(fig,

‎quantdigger/kernel/datastruct.py‎

Lines changed: 78 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,20 @@ def arg_to_type(self, arg):
4545
return self.tdict[arg.upper()]
4646
else:
4747
return arg
48-
48+
49+
50+
class Captial(object):
51+
""" 账号资金 """
52+
def __init__(self, dt, contract, type_, side, direction, price, quantity):
53+
self.broker_id = None
54+
self.account_id = None
55+
self.margin = None
56+
self.position_profit = None
57+
self.close_profit = None
58+
self.trading_day = None
59+
self.cash = None
60+
self.equity = None
61+
4962

5063
class PriceType(object):
5164
""" 下单类型
@@ -78,23 +91,34 @@ class Direction(object):
7891
"""
7992
LONG = 1
8093
SHORT = 2
81-
tdict = {'LONG': LONG,
94+
arg2type = {'LONG': LONG,
8295
'SHORT': SHORT
8396
}
8497

98+
type2str = { LONG: 'LONG',
99+
SHORT: 'SHORT',
100+
}
101+
85102
@classmethod
86103
def arg_to_type(self, arg):
87104
"""
88105
把用户输入参数转化为系统类型。
89106
"""
90107
if type(arg) == str:
91-
return self.tdict[arg.upper()]
108+
return self.arg2type[arg.upper()]
92109
else:
93110
return arg
94111

112+
@classmethod
113+
def type_to_str(self, type):
114+
return self.type2str[type]
115+
95116

96117
class Transaction(object):
97118
""" 成交记录。
119+
120+
:ivar ref: 本地编号
121+
:vartype ref: int
98122
99123
:ivar id: 成交编号
100124
:vartype id: :class:`OrderID`
@@ -123,12 +147,13 @@ class Transaction(object):
123147
:ivar commission: 佣金百分比
124148
:vartype commission: float
125149
126-
:ivar assure_ratio: 保证金比例。
127-
:vartype assure_ratio: float
150+
:ivar margin_ratio: 保证金比例。
151+
:vartype margin_ratio: float
128152
"""
129153
def __init__(self, order=None):
130154
if order:
131155
self.id = order.id
156+
self.ref = order.ref
132157
self.contract = order.contract
133158
self.direction = order.direction
134159
self.price = order.price
@@ -137,7 +162,7 @@ def __init__(self, order=None):
137162
self.datetime = order.datetime
138163
self.price_type = order.price_type
139164
self.commission = 0
140-
self.assure_ratio = 1
165+
self.margin_ratio = 1
141166

142167
def __hash__(self):
143168
if hasattr(self, '_hash'):
@@ -160,14 +185,15 @@ def profit(self, new_price):
160185
profit += (self.price - new_price) * self.quantity
161186
return profit
162187

163-
def deposit(self, new_price):
188+
def margin(self, new_price):
164189
""" 根据当前价格计算这笔交易的保证金。
165190
166191
:param float new_price: 当前价格。
167192
:return: 保证金。
168193
:rtype: float
169194
"""
170-
return self.price * self.quantity * self.assure_ratio
195+
price = self.price if self.contract.is_stock else new_price
196+
return price * self.quantity * self.margin_ratio
171197

172198

173199
class OrderID(object):
@@ -208,7 +234,10 @@ def __ge__(self, other):
208234
class Order(object):
209235
""" 订单
210236
211-
:ivar id: 成交编号
237+
:ivar ref: 本地编号
238+
:vartype ref: int
239+
240+
:ivar id: 报单编号
212241
:vartype id: :class:`OrderID`
213242
214243
:ivar contract: 合约。
@@ -233,6 +262,7 @@ class Order(object):
233262
:vartype price_type: :class:`PriceType`
234263
"""
235264
def __init__(self, dt, contract, type_, side, direction, price, quantity):
265+
self.ref = OrderID.next_order_id()
236266
self.id = OrderID.next_order_id()
237267
self.contract = contract
238268
self.direction = direction
@@ -274,6 +304,7 @@ def __init__(self, str_contract):
274304
assert False
275305
self.exch_type = exchange # 用'stock'表示中国股市
276306
self.code = code
307+
self._is_stock = True if exchange == 'stock' else False
277308

278309
def __str__(self):
279310
""""""
@@ -286,19 +317,22 @@ def __hash__(self):
286317
self._hash = hash(self.__str__())
287318
return self._hash
288319

320+
@property
321+
def is_stock(self):
322+
""" 是否是股票"""
323+
return self._is_stock
324+
289325
@classmethod
290326
def get_trading_interval(self, contract):
291327
""" 获取合约的交易时段。"""
292328
pass
293329

294330
@classmethod
295-
def get_assure_ratio(self, contract):
331+
def get_margin_ratio(self, contract):
296332
""" 获取合约的交易时段。"""
297333
pass
298334

299335

300-
301-
302336
class Period(object):
303337
""" 周期 """
304338
#class Type(Enum):
@@ -387,22 +421,51 @@ def __init__(self, order, transaction):
387421

388422
@property
389423
def datetime(self):
424+
""" 持仓日期 """
390425
return self.transaction.datetime
391426

392427
@property
393428
def price(self):
394-
""" 成交价格"""
429+
""" 成交价格 """
395430
return self.transaction.price
396431

397432
@property
398-
def assure_ratio(self):
433+
def margin_ratio(self):
399434
""" 保证金比例 """
400-
return self.transaction.assure_ratio
435+
return self.transaction.margin_ratio
401436

402437
@property
403438
def direction(self):
404439
return self.transaction.direction
405440

441+
@property
442+
def margin(self, new_price):
443+
""" 持仓的保证金占用 """
444+
return self.transaction.margin(new_price);
445+
446+
def profit(self, new_price):
447+
""" 持仓盈亏 """
448+
return self.profit(new_price)
449+
450+
@property
451+
def close_profit(self):
452+
""" 平仓盈亏 """
453+
pass
454+
455+
@property
456+
def pre_margin(self, new_price):
457+
""" 昨日保证金占用 """
458+
pass
459+
460+
@property
461+
def cost(self):
462+
""" 持仓成本 """
463+
return self.price * self.quantity
464+
465+
466+
467+
468+
406469
#def order_time(self):
407470
#return self.order.datetime
408471

‎quantdigger/kernel/engine/blotter.py‎

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from quantdigger.kernel.engine.event import OrderEvent, Event
55
from quantdigger.kernel.datastruct import Position, TradeSide, Direction
6+
from quantdigger.util import engine_logger as logger
67

78
class Positions(object):
89
""" 当前相同合约持仓集合(可能不同时间段下单)。
@@ -27,17 +28,17 @@ def profit(self, new_price):
2728
profit += pos.transaction.profit(new_price)
2829
return profit
2930

30-
def deposit(self, new_price):
31+
def margin(self, new_price):
3132
""" 根据当前价格计算这笔交易的保证金。
3233
3334
:param float new_price: 当前价格。
3435
:return: 保证金。
3536
:rtype: float
3637
"""
37-
deposit = 0
38+
margin = 0
3839
for pos in self.positions:
39-
deposit += pos.transaction.deposit(new_price)
40-
return deposit
40+
margin += pos.transaction.margin(new_price)
41+
return margin
4142

4243

4344
class DealPosition(object):
@@ -56,9 +57,14 @@ def profit(self):
5657
""" 盈亏额 """
5758
direction = self.open.order.direction
5859
if direction == Direction.LONG:
59-
return self.close.price - self.open.price
60+
return (self.close.price - self.open.price) * self.open.quantity
6061
else:
61-
return self.open.price - self.close.price
62+
return (self.open.price - self.close.price) * self.open.quantity
63+
64+
@property
65+
def quantity(self):
66+
""" 成交量 """
67+
return self.open.quantity
6268

6369
@property
6470
def open_datetime(self):
@@ -172,21 +178,28 @@ def _update_status(self, dt):
172178
dh['datetime'] = dt
173179
dh['commission'] = self.current_holdings['commission']
174180
profit = 0
175-
deposit = 0
181+
margin = 0
176182

177183
# 计算当前持仓历史盈亏。
178184
# 以close价格替代市场价格。
185+
is_stock = True # 默认是股票回测
179186
for contract, pos_info in self.current_positions.iteritems():
180187
new_price = self._bars[contract].close
181188
profit += pos_info.profit(new_price)
182-
## @bug 昨持仓的,可能是按昨日保证金,一天一结?
183-
deposit += pos_info.deposit(new_price)
189+
## @todo 用昨日结算价计算保证金
190+
margin += pos_info.margin(new_price)
191+
if not contract.is_stock:
192+
is_stock = False #
184193

185194
# 当前权益 = 初始资金 - 佣金 + 历史持仓盈亏 + 当前持仓历史盈亏
186195
dh['equity'] = self._init_captial - self.current_holdings['commission'] + self.current_holdings['history_profit'] + profit
187-
dh['cash'] = dh['equity'] - deposit
196+
dh['cash'] = dh['equity'] - margin
188197
if dh['cash'] < 0:
189-
raise Exception('你已经破产!')
198+
if not is_stock:
199+
# 如果是期货需要追加保证金
200+
## @bug 如果同时交易期货和股票,就有问题。
201+
raise Exception('需要追加保证金!')
202+
190203
self.current_holdings['cash'] = dh['cash']
191204
self.current_holdings['equity'] = dh['equity']
192205
self.all_holdings.append(dh)
@@ -202,7 +215,7 @@ def update_signal(self, event):
202215
self.events.put(OrderEvent(order))
203216
valid_orders.append(order)
204217
else:
205-
assert False
218+
assert(False and "无效合约")
206219
self._open_orders.extend(valid_orders)
207220
self.all_orders.extend(valid_orders)
208221
#print "Receive %d signals!" % len(event.orders)
@@ -255,8 +268,8 @@ def _update_positions(self, order, trans):
255268
break
256269

257270
else:
258-
assert False
259271
position.quantity -= left_vol
272+
to_delete.add(position)
260273
left_vol = 0
261274
break
262275
p.positions -= to_delete
@@ -287,7 +300,12 @@ def _valid_order(self, order):
287300
if pos.total < 0:
288301
return True
289302
except KeyError:
303+
# 没有持有该合约
304+
logger.warn("不存在合约[%s]" % order.contract)
290305
return False
291306
return False
307+
elif order.side == TradeSide.KAI:
308+
if self.current_holdings['cash'] < 0:
309+
raise Exception('没有足够的资金开仓')
292310
return True
293311

0 commit comments

Comments
 (0)