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
| import datetime import backtrader as bt import traceback
class IntraDayStrategy(bt.Strategy): def __init__(self): self.order=None self.trade = None self.myposition={'buy_date':None,'size':0,'available_size':0}
def log(self, txt, dt=None): dt = dt or self.datas[0].datetime.datetime(0) print('%s, %s' % (dt.isoformat(), txt)) def notify_trade(self, trade): if trade.isclosed: print('毛收益 %0.2f, 扣佣后收益 % 0.2f, 佣金 %.2f, 市值 %.2f, 现金 %.2f' % (trade.pnl, trade.pnlcomm, trade.commission, self.broker.getvalue(), self.broker.getcash()))
def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: return
if order.status in [order.Completed]: if order.isbuy(): self.log('买单执行,%s, %.2f, %i' % (order.data._name, order.executed.price, order.executed.size)) self.myposition['buy_date']=order.data.datetime.date(0) self.myposition['available_size']=self.myposition['size'] self.myposition['size']=order.executed.size
elif order.issell(): self.log('卖单执行, %s, %.2f, %i' % (order.data._name, order.executed.price, order.executed.size)) self.myposition['buy_date']=None self.myposition['available_size']=0 print('佣金 %.2f, 市值 %.2f, 现金 %.2f' % ( order.executed.comm, self.broker.getvalue(), self.broker.getcash())) else: self.log('订单作废 %s, %s, isbuy=%i, size %i, open price %.2f' % (order.data._name, order.getstatusname(), order.isbuy(), order.created.size, order.data.open[0])) self.order=None
def next(self): if self.order: return if self.myposition['buy_date']!=self.data.datetime.date(0): cash = self.broker.get_cash() size=0 if cash > 90000: size = int(cash * 0.40 / 100 / self.data.close[0]) * 100 else : size = int(cash * 0.90 / 100 / self.data.close[0]) * 100
try: if(self.data.datetime.time() == datetime.time(hour=9,minute=31,second=00)): self.buy(size=size,exectype=bt.Order.Market) except Exception: traceback.print_exc() else: if self.data.datetime.time() == datetime.time(hour=14,minute=58,second=00) \ and self.myposition['available_size'] > 0: self.sell(size=self.myposition['available_size'])
|