量化交易学习-RSI策略3

Signal方式

最近发现Backtrader还提供一种Signal的方式来编辑策略,正好最近又看了一本书里面有一个RSI策略的例子用的就是Signal的方式,就分享出来。

首先大概介绍下Backtrader的Signal策略编译方式。有不懂的查阅官方文档
官方的例子是这样的

class MySignal(bt.Indicator):
    lines = ('signal',)
    params = (('period', 30),)

    def __init__(self):
        self.lines.signal = self.data - bt.indicators.SMA(period=self.p.period)

如果self.lines.signal

大于零 就是多头信号

小于零 就是空头信号

等于 0 没有信号

backtrader里有五种不同的Signal,分Main和Exit两组。
Main 组:
LONGSHORT: 接受多头和空头两种技术信号。
比如官方的例子:

import backtrader as bt

data = bt.feeds.OneOfTheFeeds(dataname='mydataname')
cerebro.adddata(data)

cerebro.add_signal(bt.SIGNAL_LONGSHORT, MySignal)
cerebro.run()

用的就是SIGNAL_LONGSHORT

LONG:

  • 接受为多头信号
  • 如果有LONGEXIT,那用来平仓这个多头仓位
  • 如果有SHORT没有 LONGEXIT,会先平仓这个多头仓位再来一个空头单子。
    SHORT:
  • 接受空头信号
  • 如果有SHORTEXIT,那用来平仓这个空头仓位
  • 如果有LONG没有SHORTEXIT,会先平仓这个空头仓位再来一个多头单子。

Exit 组:

  • LONGEXIT: 空头信号用来平掉多头仓位
  • SHORTEXIT: 多头信号用来平掉空头仓位

基本策略

  • 当股票的14日RSI值到达超卖信号30时做多,达到50时平仓
  • 当股票的14日RSI值到达超买信号70时做空,达到50时平仓

放代码

from datetime import datetime
import backtrader as bt
from MyBuySell import MyBuySell
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])

# create a Stratey
class RsiSignalStrategy(bt.SignalStrategy):
    params = dict(
		rsi_periods=14,
				  rsi_upper=70,
				  rsi_lower=30,
				  rsi_mid=50
	)

    def __init__(self):

        # add RSI indicator
        rsi = bt.indicators.RSI(period=self.p.rsi_periods,
                                upperband=self.p.rsi_upper,
                                lowerband=self.p.rsi_lower)

        # add RSI from TA-lib just for reference
        bt.talib.RSI(self.data, plotname='TA_RSI')

        # long condition (with exit)
        rsi_signal_long = bt.ind.CrossUp(rsi, self.p.rsi_lower, plot=False)
        # 加入多头信号一,就是14日RSI值上穿30
        self.signal_add(bt.SIGNAL_LONG, rsi_signal_long)
        # LONGEXIT: short indications are taken to exit long positions
		# 加入多头退出信号,14日RSi值大于50
        self.signal_add(bt.SIGNAL_LONGEXIT, -(rsi > self.p.rsi_mid))

        # short condition (with exit)
        rsi_signal_short = -bt.ind.CrossDown(rsi, self.p.rsi_upper, plot=False)
        # 加入空头信号,也就是14日RSI值下穿70。
        self.signal_add(bt.SIGNAL_SHORT, rsi_signal_short)
		# SHORTEXIT: long indications are taken to exit short positions
		# 加入空头退出信号,14日RSi值小于50
        self.signal_add(bt.SIGNAL_SHORTEXIT, rsi < self.p.rsi_mid)

# Datas are in a subfolder of the samples. Need to find where the script is
# because it could have been called from anywhere
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, '600519-1.csv')
# Create a Data Feed
data = bt.feeds.GenericCSVData(
	dataname=datapath,
	nullvalue=0.0,
	dtformat=('%Y-%m-%d'),
	datetime=0,
	open=1,
	high=2,
	low=3,
	close=4,
	volume=5,
	openinterest=-1
)

# create a Cerebro entity
cerebro = bt.Cerebro(stdstats = False)

# # set up the backtest
cerebro.addstrategy(RsiSignalStrategy)
cerebro.adddata(data)
cerebro.broker.setcash(1000.0)
cerebro.broker.setcommission(commission=0.001)
cerebro.addobserver(MyBuySell)
cerebro.addobserver(bt.observers.Value)
cerebro.run()
cerebro.plot(iplot=True, volume=False)

结果看起来,我感觉抓的还是挺准的
在这里插入图片描述

用到的CSV文件,看我RSI策略的前面二篇

量化交易学习-RSI策略1
量化交易学习-RSI策略2
其中用到的MyBuySell.py代码

import backtrader as bt

class MyBuySell(bt.observers.BuySell):
    plotlines = dict(
        buy=dict(marker='^', markersize=8.0, color='blue', fillstyle='full'),
        sell=dict(marker='v', markersize=8.0, color='red', fillstyle='full')
    )

希望大家多给我意见。本人没有什么编程背景,有任何问题,欢迎在本文下方留言,或者将问题发送至邮箱: [email protected]
谢谢大家!

免责声明
本内容仅作为学术参考和代码实例,仅供参考,不对投资决策提供任何建议。本人不承担任何人因使用本系列中任何策略、观点等内容造成的任何直接或间接损失。

猜你喜欢

转载自www.cnblogs.com/CopperBat/p/12733718.html
今日推荐