from datetime import datetime
import backtrader as bt
import pandas as pd
class SimpleMovingAverage(bt.Strategy):
"""
主策略程序
"""
params = (("maperiod", 17),) # 全局设定交易策略的参数
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 log(self, txt, dt=None):
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def next(self):
"""
执行逻辑
"""
if self.order: # 检查是否有指令等待执行,
return
if self.data_close[0] > self.sma[0]:# 执行卖出条件判断:收盘价格高于日均线
if self.position: # 检查是否持仓
self.order = self.sell(size=20000)
if self.data_close[0] < self.sma[0]: # 执行买入条件判断:收盘价格跌破日均线
self.order = self.buy(size=20000)
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('BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
elif order.issell():
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def get_data_byakshare(code,start_date,end_date):
fund_etf_hist_sina_df = ak.fund_etf_hist_sina(symbol=code)
df=fund_etf_hist_sina_df.loc[(fund_etf_hist_sina_df['date'] >= start_date) & (fund_etf_hist_sina_df['date'] <= end_date)]
# print(df)
df.columns = ['trade_date', 'open', 'high', 'low', 'close','volume']
# df.loc[:, 'trade_date'] = pd.to_datetime(df['trade_date'])
df.set_index('trade_date', inplace=True)
df.index = pd.to_datetime(df.index)
# df.ffill()
return df
cerebro = bt.Cerebro()
cerebro.addstrategy(SimpleMovingAverage)
start_date = datetime(2024, 3, 1) # 回测开始时间
end_date = datetime(2024, 9, 1) # 回测结束时间
stock_code = "sz159607"
data = get_data_byakshare(stock_code,start_date.date(),end_date.date())
datafeed = bt.feeds.PandasData(dataname=data,
fromdate=start_date,
todate=end_date)
cerebro.adddata(datafeed,name=stock_code)
cerebro.broker.setcash(100000.0)
# cerebro.addsizer(bt.sizers.FixedSize, stake=10)
cerebro.broker.setcommission(commission=0.002)
print('组合初始值: %.2f' % cerebro.broker.getvalue())
result=cerebro.run()
print('组合终结值: %.2f' % cerebro.broker.getvalue())
# cerebro.plot()
组合初始值: 100000.00
2024-04-16, BUY EXECUTED, Price: 0.71, Cost: 14300.00, Comm 28.60
2024-04-17, BUY EXECUTED, Price: 0.71, Cost: 14220.00, Comm 28.44
2024-04-18, BUY EXECUTED, Price: 0.71, Cost: 14120.00, Comm 28.24
2024-04-19, BUY EXECUTED, Price: 0.70, Cost: 14020.00, Comm 28.04
2024-04-22, BUY EXECUTED, Price: 0.71, Cost: 14140.00, Comm 28.28
2024-04-23, BUY EXECUTED, Price: 0.73, Cost: 14680.00, Comm 29.36
2024-04-24, SELL EXECUTED, Price: 0.76, Cost: 14246.67, Comm 30.36
2024-04-25, SELL EXECUTED, Price: 0.77, Cost: 14246.67, Comm 30.80
2024-04-26, SELL EXECUTED, Price: 0.77, Cost: 14246.67, Comm 30.96
2024-04-29, SELL EXECUTED, Price: 0.80, Cost: 14246.67, Comm 31.92
2024-04-30, SELL EXECUTED, Price: 0.80, Cost: 14246.67, Comm 31.80
2024-05-06, SELL EXECUTED, Price: 0.84, Cost: 14246.67, Comm 33.44
2024-05-27, BUY EXECUTED, Price: 0.84, Cost: 16800.00, Comm 33.60
2024-05-28, SELL EXECUTED, Price: 0.85, Cost: 16800.00, Comm 33.96
2024-05-29, BUY EXECUTED, Price: 0.84, Cost: 16760.00, Comm 33.52
2024-05-30, BUY EXECUTED, Price: 0.82, Cost: 16440.00, Comm 32.88
2024-05-31, BUY EXECUTED, Price: 0.83, Cost: 16580.00, Comm 33.16
2024-06-03, BUY EXECUTED, Price: 0.82, Cost: 16360.00, Comm 32.72
2024-06-04, BUY EXECUTED, Price: 0.82, Cost: 16380.00, Comm 32.76
2024-06-05, BUY EXECUTED, Price: 0.83, Cost: 16520.00, Comm 33.04
2024-06-06, Order Canceled/Margin/Rejected
2024-06-07, Order Canceled/Margin/Rejected
2024-06-11, Order Canceled/Margin/Rejected
2024-06-12, Order Canceled/Margin/Rejected
2024-06-13, Order Canceled/Margin/Rejected
2024-06-14, Order Canceled/Margin/Rejected
2024-06-17, Order Canceled/Margin/Rejected
2024-06-18, Order Canceled/Margin/Rejected
2024-06-19, Order Canceled/Margin/Rejected
2024-06-20, SELL EXECUTED, Price: 0.84, Cost: 16506.67, Comm 33.48
2024-06-21, SELL EXECUTED, Price: 0.82, Cost: 16506.67, Comm 32.76
2024-06-24, BUY EXECUTED, Price: 0.80, Cost: 16040.00, Comm 32.08
2024-06-25, BUY EXECUTED, Price: 0.80, Cost: 16080.00, Comm 32.16
2024-06-26, Order Canceled/Margin/Rejected
2024-06-27, Order Canceled/Margin/Rejected
2024-06-28, Order Canceled/Margin/Rejected
2024-07-01, Order Canceled/Margin/Rejected
2024-07-02, Order Canceled/Margin/Rejected
2024-07-03, Order Canceled/Margin/Rejected
2024-07-04, Order Canceled/Margin/Rejected
2024-07-05, Order Canceled/Margin/Rejected
2024-07-08, Order Canceled/Margin/Rejected
2024-07-09, Order Canceled/Margin/Rejected
2024-07-10, Order Canceled/Margin/Rejected
2024-07-11, Order Canceled/Margin/Rejected
2024-07-12, SELL EXECUTED, Price: 0.82, Cost: 16357.78, Comm 32.68
2024-07-15, SELL EXECUTED, Price: 0.82, Cost: 16357.78, Comm 32.88
2024-07-16, SELL EXECUTED, Price: 0.80, Cost: 16357.78, Comm 32.04
2024-07-17, SELL EXECUTED, Price: 0.80, Cost: 16357.78, Comm 31.88
2024-07-18, SELL EXECUTED, Price: 0.79, Cost: 16357.78, Comm 31.48
2024-07-19, BUY EXECUTED, Price: 0.79, Cost: 15700.00, Comm 31.40
2024-07-22, BUY EXECUTED, Price: 0.78, Cost: 15560.00, Comm 31.12
2024-07-23, BUY EXECUTED, Price: 0.80, Cost: 15900.00, Comm 31.80
2024-07-24, BUY EXECUTED, Price: 0.78, Cost: 15620.00, Comm 31.24
2024-07-25, BUY EXECUTED, Price: 0.77, Cost: 15360.00, Comm 30.72
2024-07-26, Order Canceled/Margin/Rejected
2024-07-29, Order Canceled/Margin/Rejected
2024-07-30, Order Canceled/Margin/Rejected
2024-07-31, Order Canceled/Margin/Rejected
2024-08-01, Order Canceled/Margin/Rejected
2024-08-02, Order Canceled/Margin/Rejected
2024-08-05, Order Canceled/Margin/Rejected
2024-08-06, Order Canceled/Margin/Rejected
2024-08-07, Order Canceled/Margin/Rejected
2024-08-08, Order Canceled/Margin/Rejected
2024-08-09, Order Canceled/Margin/Rejected
2024-08-12, SELL EXECUTED, Price: 0.77, Cost: 15749.63, Comm 30.80
2024-08-13, SELL EXECUTED, Price: 0.78, Cost: 15749.63, Comm 31.00
2024-08-14, SELL EXECUTED, Price: 0.78, Cost: 15749.63, Comm 31.16
2024-08-15, SELL EXECUTED, Price: 0.76, Cost: 15749.63, Comm 30.48
2024-08-16, SELL EXECUTED, Price: 0.78, Cost: 15749.63, Comm 31.04
2024-08-19, SELL EXECUTED, Price: 0.80, Cost: 15749.63, Comm 31.88
2024-08-28, BUY EXECUTED, Price: 0.74, Cost: 14860.00, Comm 29.72
2024-08-29, BUY EXECUTED, Price: 0.72, Cost: 14440.00, Comm 28.88
2024-08-30, BUY EXECUTED, Price: 0.74, Cost: 14740.00, Comm 29.48
组合终结值: 106851.96