from __future__ import (absolute_import, division, print_function, unicode_literals) # 低买高卖策略 import backtrader as bt class LowBuyHighSellStrategy(bt.Strategy): def log(self, txt, dt=None): ''' Logging function for this strategy''' if dt is None: dt = self.datas[0].datetime.date(0) if len(self) > 0 else 'No Data' print('%s, %s' % (dt, txt)) def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close self.log('Strategy initialized', dt='Initialization') def next(self): # Log the current date and close price self.log('Date: %s, Close: %.2f' % (self.datas[0].datetime.date(0), self.dataclose[0])) self.log('High: %.2f, Low: %.2f' % (self.datas[0].high[0], self.datas[0].low[0])) # Simple trading logic if self.dataclose[0] < 17500: self.log('BUY CREATE, Date: %s, Price: %.2f, Position: %d' % (self.datas[0].datetime.date(0), self.dataclose[0], self.position.size)) self.buy() elif self.dataclose[0] > 47500 and self.position.size > 0: self.log('SELL CREATE, Date: %s, Price: %.2f, Position: %d' % (self.datas[0].datetime.date(0), self.dataclose[0], self.position.size)) self.sell()