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
| from datetime import datetime
import backtrader as bt import matplotlib.pyplot as plt import akshare as ak import pandas as pd
plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams["axes.unicode_minus"] = False
stock_hfq_df = ak.stock_zh_a_hist(symbol="000001", adjust="hfq").iloc[:, :6]
stock_hfq_df.columns = [ 'date', 'open', 'close', 'high', 'low', 'volume', ]
stock_hfq_df.index = pd.to_datetime(stock_hfq_df['date'])
class MyStrategy(bt.Strategy): """ 主策略程序 """ params = (("maperiod", 20),)
def __init__(self): """ 初始化函数 """ self.data_close = self.datas[0].close self.order = None self.buy_price = None self.buy_comm = None self.sma = bt.indicators.SimpleMovingAverage( self.datas[0], period=self.params.maperiod )
def next(self): """ 执行逻辑 """ if self.order: return if not self.position: if self.data_close[0] > self.sma[0]: self.order = self.buy(size=100) else: if self.data_close[0] < self.sma[0]: self.order = self.sell(size=100)
cerebro = bt.Cerebro() start_date = datetime(1991, 4, 3) end_date = datetime(2020, 6, 16) data = bt.feeds.PandasData(dataname=stock_hfq_df, fromdate=start_date, todate=end_date) cerebro.adddata(data) cerebro.addstrategy(MyStrategy) start_cash = 1000000 cerebro.broker.setcash(start_cash) cerebro.broker.setcommission(commission=0.002) cerebro.run()
port_value = cerebro.broker.getvalue() pnl = port_value - start_cash
print(f"初始资金: {start_cash}\n回测期间:{start_date.strftime('%Y%m%d')}:{end_date.strftime('%Y%m%d')}") print(f"总资金: {round(port_value, 2)}") print(f"净收益: {round(pnl, 2)}")
cerebro.plot(style='candlestick')
|