加入交易信号二 RSI的“黄金交叉”与“死亡交叉”
用Ta-Lib计算6日的RSI值和24日的RSI值
- 当RSI6>70或者RSI6向下穿过RSI24时,为卖出信号。
- 当RSI6<30或者RSI6向上穿过RSI24时,为买入信号。
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
# Import the backtrader platform
import backtrader as bt
# Create a Stratey
class TestStrategy(bt.Strategy):
params = (
('RSI6period', 6),
('RSI24period', 24),
)
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 __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
# To keep track of pending orders and buy price/commission
self.order = None
self.buyprice = None
self.buycomm = None
# 添加Ta-Lib RSI指标
self.RSI6=bt.talib.RSI(self.data, timeperiod= self.p.RSI6period)
self.RSI24=bt.talib.RSI(self.data, timeperiod= self.p.RSI24period)
self.crossover = bt.ind.CrossOver(self.RSI6, self.RSI24) # 交叉信号
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 enough cash
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: # Sell
self.log(