-
Notifications
You must be signed in to change notification settings - Fork 8
/
sample.py
80 lines (59 loc) · 2.43 KB
/
sample.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
from pyalgotrade import plotter, strategy
from pyalgotrade.bar import Frequency
from pyalgotrade.barfeed.csvfeed import GenericBarFeed
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.technical import ma
from pyalgotrade_mootdx import tools
class Strategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
super(Strategy, self).__init__(feed)
self.__position = None
self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 150)
self.__instrument = instrument
self.getBroker()
def onEnterOk(self, position):
execInfo = position.getEntryOrder().getExecutionInfo()
self.info("买入 %.2f" % (execInfo.getPrice()))
def onEnterCanceled(self, position):
self.__position = None
def onExitOk(self, position):
execInfo = position.getExitOrder().getExecutionInfo()
self.info("卖出 %.2f" % (execInfo.getPrice()))
self.__position = None
def onExitCanceled(self, position):
# If the exit was canceled, re-submit it.
self.__position.exitMarket()
def getSMA(self):
return self.__sma
def onBars(self, bars):
# 每一个数据都会抵达这里,就像becktest中的next
# Wait for enough bars to be available to calculate a SMA.
if self.__sma[-1] is None:
return
# bar.getTyoicalPrice = (bar.getHigh() + bar.getLow() + bar.getClose())/ 3.0
bar = bars[self.__instrument]
# If a position was not opened, check if we should enter a long position.
if self.__position is None:
if bar.getPrice() > self.__sma[-1]:
# 开多头.
self.__position = self.enterLong(self.__instrument, 100, True)
# 平掉多头头寸.
elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive():
self.__position.exitMarket()
def main():
instruments = ["600036"]
feeds = tools.build_feed(instruments, 2017, 2018, "histdata")
# 3.实例化策略
strat = Strategy(feeds, instruments[0])
# 4.设置指标和绘图
ratio = sharpe.SharpeRatio()
strat.attachAnalyzer(ratio)
plter = plotter.StrategyPlotter(strat)
# 5.运行策略
strat.run()
strat.info("最终收益: %.2f" % strat.getResult())
# 6.输出夏普率、绘图
strat.info("夏普比率: " + str(ratio.getSharpeRatio(0)))
# plter.plot()
if __name__ == '__main__':
main()