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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
| import argparse import datetime
# 导入backtrader相关包 import backtrader as bt import backtrader.feeds as btfeeds import backtrader.indicators as btind
# 交易策略 class SMACrossOver(bt.Strategy): params = ( ('stake', 1), # 交易股数 ('period', 30), # 周期长度 )
def log(self, txt, dt=None): ''' Logging function fot this strategy''' dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt))
# 打印订单信息,可选 def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: # Buy/Sell order submitted/accepted to/by broker - Nothing to do return
# Check if an order has been completed # Attention: broker could reject order if not enougth cash if order.status in [order.Completed, order.Canceled, order.Margin]: if order.isbuy(): self.log( 'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) else: # Sell self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) # 打印交易信息,可选 def notify_trade(self, trade): if trade.isclosed: self.log('TRADE PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm))
# 初始化策略属性、指标,必须 def __init__(self): sma = btind.SMA(self.data, period=self.p.period) # > 0 crossing up / < 0 crossing down self.buysell_sig = btind.CrossOver(self.data, sma)
# 交易逻辑实现,必须 def next(self): if self.buysell_sig > 0: self.log('BUY CREATE, %.2f' % self.data.close[0]) self.buy(size=self.p.stake) # keep order ref to avoid 2nd orders
elif self.position and self.buysell_sig < 0: self.log('SELL CREATE, %.2f' % self.data.close[0]) self.sell(size=self.p.stake)
def runstrategy(): args = parse_args()
# 实例化cerebro cerebro = bt.Cerebro()
# Get the dates from the args fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d') todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
# 从csv文件读取数据 data = btfeeds.BacktraderCSVData( dataname=args.data, fromdate=fromdate, todate=todate)
# 将数据传给cerebro cerebro.adddata(data)
# 添加策略 cerebro.addstrategy(SMACrossOver, period=args.period, stake=args.stake)
# 设置初始资金 cerebro.broker.setcash(args.cash)
commtypes = dict( none=None, perc=bt.CommInfoBase.COMM_PERC, fixed=bt.CommInfoBase.COMM_FIXED)
# 设置交易佣金 cerebro.broker.setcommission(commission=args.comm, mult=args.mult, margin=args.margin, percabs=not args.percrel, commtype=commtypes[args.commtype], stocklike=args.stocklike)
# 启动回测 cerebro.run()
# 绘图 if args.plot: cerebro.plot(numfigs=args.numfigs, volume=False)
# 从命令行解析参数 def parse_args(): parser = argparse.ArgumentParser( description='Commission schemes', formatter_class=argparse.ArgumentDefaultsHelpFormatter,)
parser.add_argument('--data', '-d', default='../../datas/2006-day-001.txt', help='data to add to the system')
parser.add_argument('--fromdate', '-f', default='2006-01-01', help='Starting date in YYYY-MM-DD format')
parser.add_argument('--todate', '-t', default='2006-12-31', help='Starting date in YYYY-MM-DD format')
parser.add_argument('--stake', default=1, type=int, help='Stake to apply in each operation')
parser.add_argument('--period', default=30, type=int, help='Period to apply to the Simple Moving Average')
parser.add_argument('--cash', default=10000.0, type=float, help='Starting Cash')
parser.add_argument('--comm', default=2.0, type=float, help=('Commission factor for operation, either a' 'percentage or a per stake unit absolute value'))
parser.add_argument('--mult', default=10, type=int, help='Multiplier for operations calculation')
parser.add_argument('--margin', default=2000.0, type=float, help='Margin for futures-like operations')
parser.add_argument('--commtype', required=False, default='none', choices=['none', 'perc', 'fixed'], help=('Commission - choose none for the old' ' CommissionInfo behavior'))
parser.add_argument('--stocklike', required=False, action='store_true', help=('If the operation is for stock-like assets or' 'future-like assets'))
parser.add_argument('--percrel', required=False, action='store_true', help=('If perc is expressed in relative xx% rather' 'than absolute value 0.xx'))
# -p或--plot 需要画图 parser.add_argument('--plot', '-p', action='store_true', help='Plot the read data')
parser.add_argument('--numfigs', '-n', default=1, help='Plot using numfigs figures')
return parser.parse_args()
# 主函数 if __name__ == '__main__': runstrategy()
|