Python代码实现的完整策略
时间: 2023-08-14 07:18:22 浏览: 199
好的,下面是Python代码实现的完整策略:
```python
import backtrader as bt
import tushare as ts
# 获取数据
data = ts.get_k_data('000001', start='2010-01-01', end='2021-07-01')
data = data.set_index('date')
data = data[['open', 'high', 'low', 'close', 'volume']]
data.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
data = bt.feeds.PandasData(dataname=data)
# 定义策略
class MyStrategy(bt.Strategy):
params = (
('macd_fast', 12),
('macd_slow', 26),
('macd_signal', 9),
('bb_period', 20),
('bb_dev', 2),
('printlog', False),
)
def __init__(self):
self.macd = bt.indicators.MACD(
self.data,
period_me1=self.params.macd_fast,
period_me2=self.params.macd_slow,
period_signal=self.params.macd_signal,
)
self.bb = bt.indicators.BollingerBands(
self.data,
period=self.params.bb_period,
devfactor=self.params.bb_dev,
)
self.order = None
self.buyprice = None
self.buycomm = None
def log(self, txt, dt=None, doprint=False):
if self.params.printlog or doprint:
dt = dt or self.data.datetime[0]
print('%s, %s' % (dt.date(), txt))
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
else:
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 next(self):
if self.order:
return
if not self.position:
if self.macd.macd[0] > self.macd.signal[0] and self.data.close[0] > self.bb.lines.top[0]:
self.log('BUY CREATE, %.2f' % self.data.close[0])
self.order = self.buy()
else:
if self.data.close[0] < self.bb.lines.mid[0]:
self.log('SELL CREATE, %.2f' % self.data.close[0])
self.order = self.sell()
def stop(self):
self.log('(Fast %d, Slow %d, Signal %d, BB %d, Dev %d) Ending Value %.2f' %
(self.params.macd_fast, self.params.macd_slow, self.params.macd_signal, self.params.bb_period, self.params.bb_dev, self.broker.getvalue()), doprint=True)
# 运行策略
cerebro = bt.Cerebro()
cerebro.addstrategy(MyStrategy)
cerebro.adddata(data)
cerebro.broker.setcash(1000000)
cerebro.broker.setcommission(commission=0.001)
cerebro.run()
cerebro.plot()
```
在这个策略中,我们使用了tushare库来获取数据,并将其导入到backtrader中。然后,我们定义了一个名为MyStrategy的策略,并使用MACD和Bollinger Bands指标来构建策略。在next()方法中,我们根据指标的信号来判断是否开仓或平仓。最后通过cerebro来运行策略并输出回测结果。
需要注意的是,这只是一个简单的示例策略,实际应用中需要根据具体情况进行修改和优化。
阅读全文