B站配套视频教程观看
使用PyAlgoTrade回测双均线策略

双均线策略:长短周期均线,通过金叉死叉的方式买入卖出股票,获取收益的策略。

回顾上节课代码的部分,上节课完成了可视化代码的部分, 主要使用PyAlgoTradeplotter模块,对SMA的数据,Simple Returns的数据进行了可视化,我们也利用了returns这个类来获取收益,然后将实例化的returns类去赋予给mystrategy

你会发现,所有的核心就是:我计算出来的数据,将这个数据作为mystrategy的属性,这样就可以在mystrategy里面给各个函数使用了。

现在是单均线,如果我要使用双均线应该怎么实现呢?

一、实操找到最优质双均线

创建变量 修改构造函数:

class MyStrategy(strategy.BacktestingStrategy):def __init__(self, feed, instrument, smaPeriod1, smaPeriod2):super(MyStrategy, self).__init__(feed, 10000)self.__position = Noneself.__instrument = instrument# # We'll use adjusted close values instead of regular close values.# self.setUseAdjustedValues(True)self.__sma1 = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod1)self.__sma2 = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod2)

设置2个返回值函数:

    def getSMA1(self):return self.__sma1def getSMA2(self):return self.__sma2

修改策略:

    def onBars(self, bars):# Wait for enough bars to be available to calculate a SMA.if self.__sma2[-1] is None:returnbar = bars[self.__instrument]# If a position was not opened, check if we should enter a long position.if self.__position is None:#短期均价>长期均价 买入if self.__sma1[-1] > self.__sma2[-1]:# Enter a buy market order for 10 shares. The order is good till canceled.self.__position = self.enterLong(self.__instrument, 100, True)# 短期均价<长期均价卖出elif self.__sma1[-1] < self.__sma2[-1] and not self.__position.exitActive():self.__position.exitMarket()

运行策略:

def run_strategy(smaPeriod1, smaPeriod2):# Load the bar feed from the CSV fileinstruments = ["000001"]feeds = tools.build_feed(instruments, 2018, 2021, "histdata")#print(feeds)# Evaluate the strategy with the feed's bars.myStrategy = MyStrategy(feeds, instruments[0], smaPeriod1, smaPeriod2)myStrategy.run()# 打印总持仓:(cash + shares * price) (持有现金 + 股数*价格)print(smaPeriod1, smaPeriod2, "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())# Attach a returns analyzers to the strategy.# returnsAnalyzer = returns.Returns()# myStrategy.attachAnalyzer(returnsAnalyzer)# # Attach the plotter to the strategy.# plt = plotter.StrategyPlotter(myStrategy)# # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.# plt.getInstrumentSubplot(instruments[0]).addDataSeries("SMA1", myStrategy.getSMA1())# plt.getInstrumentSubplot(instruments[0]).addDataSeries("SMA2", myStrategy.getSMA2())# # Plot the simple returns on each bar.# plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())# # Run the strategy.# myStrategy.run()# myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())# # Plot the strategy.# plt.plot()

调用运行策略:

ma1 = [5, 10, 15]
ma2 = [15, 20, 35]
for i in ma1:for j in ma2:if i<j:run_strategy(i, j)

运行:

结果来看,数据表现最好的是10661

二、可视化最优双均线

#使用pyalgotrade进行数据回测
import pyalgotrade
from pyalgotrade import strategy
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade_tushare import tools, barfeed
from pyalgotrade.technical import ma
from pyalgotrade import plotter
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.stratanalyzer import returnsdef safe_round(value, digits):if value is not None:value = round(value, digits)return valueclass MyStrategy(strategy.BacktestingStrategy):def __init__(self, feed, instrument, smaPeriod1, smaPeriod2):super(MyStrategy, self).__init__(feed, 10000)self.__position = Noneself.__instrument = instrument# # We'll use adjusted close values instead of regular close values.# self.setUseAdjustedValues(True)self.__sma1 = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod1)self.__sma2 = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod2)def getSMA1(self):return self.__sma1def getSMA2(self):return self.__sma2def onEnterOk(self, position):execInfo = position.getEntryOrder().getExecutionInfo()#self.info("BUY at $%.2f" % (execInfo.getPrice()))def onEnterCanceled(self, position):self.__position = Nonedef onExitOk(self, position):execInfo = position.getExitOrder().getExecutionInfo()#self.info("SELL at $%.2f" % (execInfo.getPrice()))self.__position = Nonedef onExitCanceled(self, position):# If the exit was canceled, re-submit it.self.__position.exitMarket()def onBars(self, bars):# Wait for enough bars to be available to calculate a SMA.if self.__sma2[-1] is None:returnbar = bars[self.__instrument]# If a position was not opened, check if we should enter a long position.if self.__position is None:#短期均价>长期均价 买入if self.__sma1[-1] > self.__sma2[-1]:# Enter a buy market order for 10 shares. The order is good till canceled.self.__position = self.enterLong(self.__instrument, 100, True)# 短期均价<长期均价卖出elif self.__sma1[-1] < self.__sma2[-1] and not self.__position.exitActive():self.__position.exitMarket()def run_strategy(smaPeriod1, smaPeriod2):# Load the bar feed from the CSV fileinstruments = ["000001"]feeds = tools.build_feed(instruments, 2018, 2021, "histdata")#print(feeds)# Evaluate the strategy with the feed's bars.myStrategy = MyStrategy(feeds, instruments[0], smaPeriod1, smaPeriod2)# myStrategy.run()# # 打印总持仓:(cash + shares * price) (持有现金 + 股数*价格)# print(smaPeriod1, smaPeriod2, "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())# Attach a returns analyzers to the strategy.returnsAnalyzer = returns.Returns()myStrategy.attachAnalyzer(returnsAnalyzer)# Attach the plotter to the strategy.plt = plotter.StrategyPlotter(myStrategy)# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.plt.getInstrumentSubplot(instruments[0]).addDataSeries("SMA1", myStrategy.getSMA1())plt.getInstrumentSubplot(instruments[0]).addDataSeries("SMA2", myStrategy.getSMA2())# Plot the simple returns on each bar.plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())# Run the strategy.myStrategy.run()myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())# Plot the strategy.plt.plot()run_strategy(5, 30)

运行:

对于双均线可视化图表的部分

蓝色的颜色的是K线,浅蓝色是短期均线, 紫色是长期均线,更平缓,然后就是买入卖出标记,这里的买入卖出标记比起单均线的策略明显要少很多,也就是开仓次数要少很多

接着看单次收益率图,从图中看到,收益并没有很好,上下浮动差不多。所以在这个情况下,可以基于很多因素进行优化。

最后看一下累计收益图,可以看到整体曲线和行情数据表现差不多 那么以上就是关于如何去利用一个已有的开源框线对我们的双均线策略进行回测的内同。到这里如果说你完全知道代码是怎么写的,那么你应该也能够实现其他的策略,比如说布林策略,通过改写这里的开仓和平仓条件就能够快速的转载请注明:虚幻私塾 » Python量化交易实战-38使用开源项目回测双均线策略获得回测图谱。

Python量化交易实战-38使用开源项目回测双均线策略相关推荐

  1. Python 量化投资实战教程(3) —A股回测MACD策略

    量化投资系列文章: Backtrader 教程 - Python 量化投资实战教程(1) Python 量化投资实战教程(2) -MACD策略(+26.9%) Python 量化投资实战教程(3) - ...

  2. python tushare backtrader股票回测双均线策略

    前言: 在前面学了点机器学习知识后,发现自己还没有一个回测框架,找了短时间学习资料,还是决定使用backtrader,至于聚宽优米那些平台感觉使用起来好像没那么自由,还是先学习下backtrader, ...

  3. 《深入浅出Python量化交易实战》:散户也能学会的数字化交易策略

    前言 您可能不知道,许多专业的交易机构已经采用设定程序完成自动化交易,通过机器语言,解密盘面的走势,从而实现持续盈利的目的. (文末送读者福利) 这并非什么秘密,他们正是借助了这样的数字化工具进行操作 ...

  4. 很燃基于掘金量化平台的《Python量化交易实战》新书介

    原 很燃!基于掘金量化平台的<Python量化交易实战>新书简介 内容简介: 在目前不断变化.蓬勃发展的中国资本市场,量化投资作为新兴的投资方法,引来越来越多的关注,使用量化投资技术的证券 ...

  5. Python量化交易实战-40easytrader开发环境安装

    B站配套视频教程观看 初始化easytrader开发环境 一.安装对象 1.1客户端安装 股票的客户端,可以是券商,比如说华泰.海通.也可以是第三方平台,东方财富.同花顺.但是由于easytrader ...

  6. Python量化交易实战-41EasyTrader自动化模拟真实交易

    B站配套视频教程观看 EasyTrader自动化模拟真实交易 来到官方文档的使用部分: https://easytrader.readthedocs.io/zh/master/usage/ 一.用法 ...

  7. 【赠书】深入浅出Python量化交易实战

    ‍‍ 本书主要以国内A股市场为例,借助第三方量化交易平台,讲述了KNN.线性模型.决策树.支持向量机.朴素贝叶斯等常见机器学习算法在交易策略中的应用,同时展示了如何对策略进行回测,以便让读者能够有效评 ...

  8. python应用于人工智能的代码_【python量化】人工智能技术在量化交易中应用的开源项目...

    这个项目收集了包括机器学习,深度学习以及强化学习在内的一些用于股票预测的模型.其中深度学习模型包括: LSTM LSTM Bidirectional LSTM 2-Path GRU GRU Bidir ...

  9. Python量化交易实战:获取股票数据并做分析处理

    量化交易(也称自动化交易)是一种应用数学模型帮助投资者进行判断,并且根据计算机程序发送的指令进行交易的投资方式,它极大地减少了投资者情绪波动的影响.量化交易的主要优势如下: 快速检测 客观.理性 自动 ...

最新文章

  1. 获取request的变量
  2. 求几亿个数中不重复元素的个数
  3. SPL--Serializable
  4. 全面讲解Python字典;--什么是字典?字典的常用方法;创建空字典并赋值,增删改查字典中的元素
  5. Effective C++学习笔记——构造/析构/拷贝运算
  6. 小明一家过桥_【练习】用python解决小明一家过桥问题
  7. 浏览器填写数据,跳转页面返回数据不消失
  8. 互站卖的分发美化版可以封装双端APP
  9. Hadoop2.2.0--Hadoop Federation、Automatic HA、Yarn完全分布式集群结构
  10. python之通过thread来实现多进程
  11. 2019年税收分类编码_您如何在2019年学习编码
  12. Android 支付宝小程序跳转
  13. WTEditor(windows窗口标题栏文字修改工具)绿色单文件版V1.0 | windows窗口标题文字怎么修改?
  14. 认识一下,JavaScript今年25岁啦
  15. Unity UGUI DoTween 学习笔记
  16. android 版本更新原理,蒲公英 - 文档中心 - SDK 自动更新机制
  17. 初始化Linux数据盘(fdisk)
  18. Linux运维07:free命令详解
  19. 积分体系与会员体系之间的那些事
  20. 【Jpeg】不同平台如何编译 jpeg-turbo 库文件

热门文章

  1. 【Grasshopper进阶】强制Grasshopper电池输入/输出参数数据结构扁平化 (i.e. Flatten/拍平/展开…)
  2. 汉文博士新测试版0.5.3.2005发布
  3. 校园一键报警柱的作用
  4. 树链剖分(四)——旅行
  5. [翻译]扫描线算法(Line Sweep Algorithm)(1)
  6. 基于Basic RF的智能家居控制系统---智能照明功能(照明端)
  7. 六,FreeRTOS之——临界资源访问
  8. linux-pclint代码检测
  9. Web开发和设计精华文章推荐【系列三】
  10. 修改AD域ladp连接数