Skip to content

Commit 6029476

Browse files
committed
删除web文件,修复demo文件夹的pip打包错误
1 parent 8ecaccd commit 6029476

533 files changed

Lines changed: 196 additions & 106943 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

quantdigger/widgets/web/angular_sites/js/lib/tinymce/.DS_Store renamed to quantdigger/demo/.DS_Store

6 KB
Binary file not shown.
File renamed without changes.

‎quantdigger/demo/plotting.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +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
67

78
def plot_result(price_data, indicators, signals, blotter):
89
"""
910
显示回测结果。
1011
"""
1112
try:
12-
blotter.create_equity_curve_dataframe()
13-
print blotter.output_summary_stats()
13+
curve = statics.create_equity_curve_dataframe(blotter.all_holdings)
14+
print statics.output_summary_stats(curve)
1415

1516
fig = plt.figure()
1617
frame = widgets.MultiWidgets(fig,
@@ -33,7 +34,7 @@ def plot_result(price_data, indicators, signals, blotter):
3334

3435
fig2 = plt.figure()
3536
ax = fig2.add_axes((0.1, 0.1, 0.9, 0.9))
36-
ax.plot(blotter.equity_curve.equity)
37+
ax.plot(curve.equity)
3738
plt.show()
3839

3940
except Exception, e:

‎quantdigger/digger/__init__.py‎

Whitespace-only changes.

‎quantdigger/digger/statics.py‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# -*- coding: utf8 -*-
2+
import pandas as pd
3+
import numpy as np
4+
5+
def create_sharpe_ratio(returns, periods=252):
6+
"""
7+
Create the Sharpe ratio for the strategy, based on a
8+
benchmark of zero (i.e. no risk-free rate information).
9+
10+
Parameters:
11+
returns - A pandas Series representing period percentage returns.
12+
periods - Daily (252), Hourly (252*6.5), Minutely(252*6.5*60) etc.
13+
"""
14+
return np.sqrt(periods) * (np.mean(returns)) / np.std(returns)
15+
16+
17+
def create_drawdowns(equity_curve):
18+
"""
19+
Calculate the largest peak-to-trough drawdown of the PnL curve
20+
as well as the duration of the drawdown. Requires that the
21+
pnl_returns is a pandas Series.
22+
23+
Parameters:
24+
pnl - A pandas Series representing period percentage returns.
25+
26+
Returns:
27+
drawdown, duration - Highest peak-to-trough drawdown and duration.
28+
"""
29+
30+
# Calculate the cumulative returns curve
31+
# and set up the High Water Mark
32+
# Then create the drawdown and duration series
33+
hwm = [0]
34+
eq_idx = equity_curve.index
35+
drawdown = pd.Series(index = eq_idx)
36+
duration = pd.Series(index = eq_idx)
37+
38+
# Loop over the index range
39+
for t in range(1, len(eq_idx)):
40+
cur_hwm = max(hwm[t-1], equity_curve[t])
41+
hwm.append(cur_hwm)
42+
drawdown[t]= hwm[t] - equity_curve[t]
43+
duration[t]= 0 if drawdown[t] == 0 else duration[t-1] + 1
44+
return drawdown.max(), duration.max()
45+
46+
47+
def create_equity_curve_dataframe(all_holdings):
48+
"""
49+
创建资金曲线对象。
50+
"""
51+
curve = pd.DataFrame(all_holdings)
52+
curve.set_index('datetime', inplace=True)
53+
curve['returns'] = curve['equity'].pct_change()
54+
curve['equity_curve'] = (1.0+curve['returns']).cumprod()
55+
return curve
56+
57+
def output_summary_stats(curve):
58+
"""
59+
统计夏普率, 回测等信息。
60+
"""
61+
total_return = curve['equity_curve'][-1]
62+
returns = curve['returns']
63+
pnl = curve['equity_curve']
64+
65+
sharpe_ratio = create_sharpe_ratio(returns)
66+
max_dd, dd_duration = create_drawdowns(pnl)
67+
68+
stats = [("Total Return", "%0.2f%%" % ((total_return - 1.0) * 100.0)),
69+
("Sharpe Ratio", "%0.2f" % sharpe_ratio),
70+
("Max Drawdown", "%0.2f%%" % (max_dd * 100.0)),
71+
("Drawdown Duration", "%d" % dd_duration)]
72+
return stats

‎quantdigger/kernel/datastruct.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,18 @@ def __hash__(self):
286286
self._hash = hash(self.__str__())
287287
return self._hash
288288

289+
@classmethod
290+
def get_trading_interval(self, contract):
291+
""" 获取合约的交易时段。"""
292+
pass
293+
294+
@classmethod
295+
def get_assure_ratio(self, contract):
296+
""" 获取合约的交易时段。"""
297+
pass
298+
299+
300+
289301

290302
class Period(object):
291303
""" 周期 """
@@ -360,6 +372,7 @@ def __hash__(self):
360372
self._hash = hash(self.__str__())
361373
return self._hash
362374

375+
363376
class Position(object):
364377
""" 单笔仓位信息。
365378

‎quantdigger/kernel/engine/api.py‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,22 @@ def cancel_order(self, orderid, sync=False):
5151
""" 撤单操作请求 """
5252
pass
5353

54-
54+
def on_transaction(self, trans):
55+
""" 委托成交回调 """
56+
pass
57+
58+
def on_tick(self, tick):
59+
""" tick数据回调 """
60+
pass
61+
62+
def on_captial(self, tick):
63+
""" 资金查询回调 """
64+
pass
65+
66+
def on_position(self, tick):
67+
""" 持仓查询回调 """
68+
pass
69+
5570

5671
class CtpTraderAPI(object):
5772
""" Ctp交易类 """
@@ -86,8 +101,24 @@ def cancel_order(self, orderid):
86101
""" 撤单操作请求 """
87102
pass
88103

104+
def on_transaction(self, trans):
105+
""" 委托成交回调 """
106+
pass
107+
108+
def on_tick(self, tick):
109+
""" tick数据回调 """
110+
pass
89111

90-
class SimulateTrader(Trader):
112+
def on_captial(self, tick):
113+
""" 资金查询回调 """
114+
pass
115+
116+
def on_position(self, tick):
117+
""" 持仓查询回调 """
118+
pass
119+
120+
121+
class SirulateTraderAPI(Trader):
91122
""" 模拟交易下单接口 """
92123
def __init__(self):
93124
pass
@@ -119,3 +150,19 @@ def order(self, order):
119150
def cancel_order(self, orderid):
120151
""" 撤单操作请求 """
121152
pass
153+
154+
def on_transaction(self, trans):
155+
""" 委托成交回调 """
156+
pass
157+
158+
def on_tick(self, tick):
159+
""" tick数据回调 """
160+
pass
161+
162+
def on_captial(self, tick):
163+
""" 资金查询回调 """
164+
pass
165+
166+
def on_position(self, tick):
167+
""" 持仓查询回调 """
168+
pass

‎quantdigger/kernel/engine/blotter.py‎

Lines changed: 53 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
# -*- coding: utf8 -*-
2-
import pandas as pd
32
from abc import ABCMeta, abstractmethod
43

54
from quantdigger.kernel.engine.event import OrderEvent, Event
65
from quantdigger.kernel.datastruct import Position, TradeSide, Direction
7-
from performance import create_sharpe_ratio, create_drawdowns
86

97
class Positions(object):
108
""" 当前相同合约持仓集合(可能不同时间段下单)。
@@ -82,6 +80,11 @@ def close_price(self):
8280
""" 平仓价格 """
8381
return self.close.price
8482

83+
@property
84+
def direction(self):
85+
""" 空头还是多头 """
86+
return self.open.order.direction
87+
8588

8689
class Blotter(object):
8790
"""
@@ -124,12 +127,10 @@ def __init__(self, timeseries, events_pool, initial_capital=5000.0):
124127
self.current_positions = {} # 当前持仓 dict of list, 包含细节。
125128
self.current_holdings = {} # 当前的资金 dict
126129

127-
self.all_positions = [] # 在所有时间点上的持仓 list of dict
128130
self.all_holdings = [] # 所有时间点上的资金 list of dict
129131
self.deal_positions = [] # 开平仓对
130132

131133
def _init_state(self):
132-
self.all_positions = [{'datetime' : self._start_date }]
133134
self.current_holdings = {
134135
'cash': self.initial_capital,
135136
'commission': 0.0,
@@ -158,62 +159,12 @@ def update_datetime(self, dt):
158159
self._datetime = dt
159160
self._update_status(dt)
160161

161-
def update_fill(self, event):
162-
"""
163-
处理委托单成交事件。
164-
"""
165-
assert event.type == Event.FILL
166-
t_order = None
167-
for i, order in enumerate(self._open_orders):
168-
if order.id == event.transaction.id:
169-
t_order = self._open_orders.pop(i)
170-
break
171-
assert(t_order)
172-
self._update_positions(t_order, event.transaction)
173-
self._update_holdings(event.transaction)
174-
175-
def update_signal(self, event):
176-
"""
177-
处理策略函数产生的下单事件。
178-
"""
179-
assert event.type == Event.SIGNAL
180-
valid_orders = []
181-
for order in event.orders:
182-
if self.valid_order(order):
183-
self.events.put(OrderEvent(order))
184-
valid_orders.append(order)
185-
else:
186-
assert False
187-
self._open_orders.extend(valid_orders)
188-
self.all_orders.extend(valid_orders)
189-
#print "Receive %d signals!" % len(event.orders)
190-
#self.generate_naive_order(event.orders)
191-
192-
def valid_order(self, order):
193-
""" 判断订单是否合法。 """
194-
if order.side == TradeSide.PING:
195-
try:
196-
pos = self.current_positions[order.contract]
197-
if order.direction == Direction.LONG:
198-
## @todo 自动改变合法仓位。
199-
if pos.total > 0:
200-
return True
201-
elif order.direction == Direction.SHORT:
202-
## @todo 自动改变合法仓位。
203-
if pos.total < 0:
204-
return True
205-
except KeyError:
206-
return False
207-
return False
208-
return True
209-
210162
def _update_status(self, dt):
211163
""" 更新历史持仓,当前权益。"""
212164
# 更新持仓历史。
213165
dp = { }
214166
dp['datetime'] = dt
215167
dp.update(self.current_positions)
216-
self.all_positions.append(dp)
217168

218169
# 更新资金历史。
219170
## @todo 由持仓历史推断资金历史。
@@ -240,6 +191,37 @@ def _update_status(self, dt):
240191
self.current_holdings['equity'] = dh['equity']
241192
self.all_holdings.append(dh)
242193

194+
def update_signal(self, event):
195+
"""
196+
处理策略函数产生的下单事件。
197+
"""
198+
assert event.type == Event.SIGNAL
199+
valid_orders = []
200+
for order in event.orders:
201+
if self._valid_order(order):
202+
self.events.put(OrderEvent(order))
203+
valid_orders.append(order)
204+
else:
205+
assert False
206+
self._open_orders.extend(valid_orders)
207+
self.all_orders.extend(valid_orders)
208+
#print "Receive %d signals!" % len(event.orders)
209+
#self.generate_naive_order(event.orders)
210+
211+
def update_fill(self, event):
212+
"""
213+
处理委托单成交事件。
214+
"""
215+
assert event.type == Event.FILL
216+
t_order = None
217+
for i, order in enumerate(self._open_orders):
218+
if order.id == event.transaction.id:
219+
t_order = self._open_orders.pop(i)
220+
break
221+
assert(t_order)
222+
self._update_positions(t_order, event.transaction)
223+
self._update_holdings(event.transaction)
224+
243225
def _update_positions(self, order, trans):
244226
## @todo 把复杂统计单独出来。
245227
""" 更新持仓 """
@@ -291,29 +273,21 @@ def _update_holdings(self, trans):
291273
if trans.side == TradeSide.PING:
292274
self.current_holdings['history_profit'] += trans.profit(trans_cost)
293275

294-
def create_equity_curve_dataframe(self):
295-
"""
296-
创建资金曲线对象。
297-
"""
298-
curve = pd.DataFrame(self.all_holdings)
299-
curve.set_index('datetime', inplace=True)
300-
curve['returns'] = curve['equity'].pct_change()
301-
curve['equity_curve'] = (1.0+curve['returns']).cumprod()
302-
self.equity_curve = curve
276+
def _valid_order(self, order):
277+
""" 判断订单是否合法。 """
278+
if order.side == TradeSide.PING:
279+
try:
280+
pos = self.current_positions[order.contract]
281+
if order.direction == Direction.LONG:
282+
## @todo 自动改变合法仓位。
283+
if pos.total > 0:
284+
return True
285+
elif order.direction == Direction.SHORT:
286+
## @todo 自动改变合法仓位。
287+
if pos.total < 0:
288+
return True
289+
except KeyError:
290+
return False
291+
return False
292+
return True
303293

304-
def output_summary_stats(self):
305-
"""
306-
统计夏普率, 回测等信息。
307-
"""
308-
total_return = self.equity_curve['equity_curve'][-1]
309-
returns = self.equity_curve['returns']
310-
pnl = self.equity_curve['equity_curve']
311-
312-
sharpe_ratio = create_sharpe_ratio(returns)
313-
max_dd, dd_duration = create_drawdowns(pnl)
314-
315-
stats = [("Total Return", "%0.2f%%" % ((total_return - 1.0) * 100.0)),
316-
("Sharpe Ratio", "%0.2f" % sharpe_ratio),
317-
("Max Drawdown", "%0.2f%%" % (max_dd * 100.0)),
318-
("Drawdown Duration", "%d" % dd_duration)]
319-
return stats

0 commit comments

Comments
 (0)