python
import backtrader as bt
import pandas as pd
class BullishEngulfingStrategy(bt.Strategy):
params = (
('stoploss_pct', 0.03), # 止损百分比
('takeprofit_pct', 0.05), # 止盈百分比
)
def __init__(self):
self.data_open = self.datas[0].open
self.data_close = self.datas[0].close
self.data_high = self.datas[0].high
self.data_low = self.datas[0].low
# 需要添加其他指标时,可在此处进行初始化
def next(self):
if self.position.size == 0: # 没有持仓
if self.bullish_engulfing(): # 看涨吞没模式
stoploss = self.data_close[0] * (1 - self.params.stoploss_pct)
takeprofit = self.data_close[0] * (1 + self.params.takeprofit_pct)
self.buy(
exectype=bt.Order.Market,
coo=False,
price=self.data_close[0],
exectype=bt.Order.Stop,
price=stoploss,
exectype=bt.Order.Limit,
price=takeprofit,
)
elif self.position.size > 0: # 持有多头仓位
if self.data_close[0] < stoploss or self.data_close[0] > takeprofit:
self.close() # 平仓
def bullish_engulfing(self):
return (
self.data_close[-2] < self.data_open[-2] and # 前一日收盘价小于开盘价
self.data_close[-1] > self.data_open[-1] and # 今日收盘价大于开盘价
self.data_close[-2] > self.data_close[-1] and # 前一日收盘价大于今日收盘价
self.data_open[-2] < self.data_close[-1] and # 前一日开盘价小于今日收盘价
abs(self.data_close[-2] - self.data_open[-2]) > abs(self.data_close[-1] - self.data_open[-1]) # 前一日的实体长于今日
)
class BearishEngulfingStrategy(bt.Strategy):
params = (
('stoploss_pct', 0.03), # 止损百分比
('takeprofit_pct', 0.05), # 止盈百分比
)
def __init__(self):
self.data_open = self.datas[0].open
self.data_close = self.datas[0].close
self.data_high = self.datas[0].high
self.data_low = self.datas[0].low
# 需要添加其他指标时,可在此处进行初始化
def next(self):
if self.position.size == 0: # 没有持仓
if self.bearish_engulfing(): # 看跌吞没模式
stoploss = self.data_close[0] * (1 + self.params.stoploss_pct)
takeprofit = self.data_close[0] * (1 - self.params.takeprofit_pct)
self.sell(
exectype=bt.Order.Market,
coo=False,
price=self.data_close[0],
exectype=bt.Order.Stop,
price=stoploss,
exectype=bt.Order.Limit,
price=takeprofit,
)
elif self.position.size < 0: # 持有空头仓位
if self.data_close[0] > stoploss or self.data_close[0] < takeprofit:
self.close() # 平仓
def bearish_engulfing(self):
return (
self.data_close[-2] > self.data_open[-2] and # 前一日收盘价大于开盘价
self.data_close[-1] < self.data_open[-1] and # 今日收盘价小于开盘价
self.data_close[-2] < self.data_close[-1] and # 前一日收盘价小于今日收盘价
self.data_open[-2] > self.data_close[-1] and # 前一日开盘价大于今日收盘价
abs(self.data_close[-2] - self.data_open[-2]) > abs(self.data_close[-1] - self.data_open[-1]) # 前一日的实体长于今日
)
if __name__ == '__main__':
cerebro = bt.Cerebro()
# 读取Excel数据
df = pd.read_excel('AAPL.xlsx')
ohlc_data = df[['Open', 'High', 'Low', 'Close', 'Volume']].reset_index().values
# 将毫秒时间戳转换为datetime格式
datetime_index = df['Date'].apply(lambda x: pd.Timestamp(x, unit='ms'))
# 将数据载入backtrader
data = bt.feeds.PandasData(
dataname=pd.DataFrame(
data=ohlc_data[:, 1:],
columns=['open', 'high', 'low', 'close', 'volume'],
index=datetime_index),
fromdate=datetime_index[0],
todate=datetime_index[-1])
cerebro.adddata(data)
# 添加看涨吞没策略
cerebro.addstrategy(BullishEngulfingStrategy,
stoploss_pct=0.03, # 止损百分比
takeprofit_pct=0.05) # 止盈百分比
# 添加看跌吞没策略
cerebro.addstrategy(BearishEngulfingStrategy,
stoploss_pct=0.03, # 止损百分比
takeprofit_pct=0.05) # 止盈百分比
cerebro.run()