PyAlgoTrade使得绘制策略执行变得非常简单

from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross class SMACrossOver(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, smaPeriod):
super(SMACrossOver, self).__init__(feed)
self.__instrument = instrument
self.__position = None
# We'll use adjusted close values instead of regular close values.
self.setUseAdjustedValues(True)
self.__prices = feed[instrument].getPriceDataSeries()
self.__sma = ma.SMA(self.__prices, smaPeriod) def getSMA(self):
return self.__sma def onEnterCanceled(self, position):
self.__position = None def onExitOk(self, position):
self.__position = None def onExitCanceled(self, position):
# If the exit was canceled, re-submit it.
self.__position.exitMarket() def onBars(self, bars):
# If a position was not opened, check if we should enter a long position.
if self.__position is None:
if cross.cross_above(self.__prices, self.__sma) > 0:
shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
# Enter a buy market order. The order is good till canceled.
self.__position = self.enterLong(self.__instrument, shares, True)
# Check if we have to exit the position.
elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
self.__position.exitMarket()
from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover # Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv") # Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20) # 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("orcl").addDataSeries("SMA", myStrategy.getSMA())
# 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()

代码正在做3件事情:

  • 从CSV文件加载Feed。
  • 使用Feed提供的栏和附带的StrategyPlotter来运行策略。
  • 制定策略
    如下样子:

作者:readilen
链接:http://www.jianshu.com/p/b90f58c6a54c
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

PyalgoTrade 绘图(七)的更多相关文章

  1. HTML5基础总结

    HTML5是HTML语言的第五次重大版本升级,新增了如下内容:1.新增<video>.<audio>标签在页面上直接播放多媒体资源;2.新增<input>标签的ty ...

  2. Python·Jupyter Notebook各种使用方法

    PythonJupyter Notebook各种使用方法记录持续更新 一 Jupyter NoteBook的安装 1 新版本Anaconda自带Jupyter 2 老版本Anacodna需自己安装Ju ...

  3. 初学者需要IPython 与 Jupyter Notebook 吗?

    ipython 是 jupyter notebook的前身并拥有ipython的全部功能         jupyter拥有 cell, markdown 整合的功能, 能同时运行代码, 而且是多组的 ...

  4. Python·Jupyter Notebook各种使用方法记录

    标签(空格分隔): Python 一 Jupyter NoteBook的安装 1 新版本Anaconda自带Jupyter 2 老版本Anacodna需自己安装Jupyter 二 更改Jupyter ...

  5. ApacheCN C/C++ 译文集 20211201 更新

    笨办法学C 中文版 前言 导言:C的笛卡尔之梦 练习0:准备 练习1:启用编译器 练习2:用Make来代替Python 练习3:格式化输出 练习4:Valgrind 介绍 练习5:一个C程序的结构 练 ...

  6. ApacheCN 数据科学译文集 20211109 更新ApacheCN 数据科学译文集 20211109 更新

    计算与推断思维 一.数据科学 二.因果和实验 三.Python 编程 四.数据类型 五.表格 六.可视化 七.函数和表格 八.随机性 九.经验分布 十.假设检验 十一.估计 十二.为什么均值重要 十三 ...

  7. ApacheCN 数据科学译文集 2020.8

    协议:CC BY-NC-SA 4.0 不要担心自己的形象,只关心如何实现目标.--<原则>,生活原则 2.3.c 在线阅读 ApacheCN 面试求职交流群 724187166 Apach ...

  8. ApacheCN Pandas 教程集

    Pandas 秘籍 零.前言 一.Pandas 基础 二.数据帧基本操作 三.开始数据分析 四.选择数据子集 五.布尔索引 六.索引对齐 七.分组以进行汇总,过滤和转换 八.将数据重组为整齐的表格 九 ...

  9. 精通 Pandas · 翻译完成

    协议:CC BY-NC-SA 4.0 欢迎任何人参与和完善:一个人可以走的很快,但是一群人却可以走的更远. 在线阅读 ApacheCN 面试求职交流群 724187166 ApacheCN 学习资源 ...

随机推荐

  1. testng日志和报告

    TestNG是通过 Listeners 或者 Reporters 生成测试报告. Listeners,即 org.testng.ITestListener 的实现,能够在测试执行过程中发出各种测试结果 ...

  2. pip 解决 ImportError: cannot import name 'main'

    当 pip 更新至最新版的时候,不管是执行 pip list 还说 pip install packageName 安装包,都会抛出一个异常 Traceback (most recent call l ...

  3. EWD简介

    Edsger Wybe Dijkstra was a principal contributor in the late 1950's to the development of the ALGOL, ...

  4. 通过IP地址和子网掩码与运算计算相关地址

    通过IP地址和子网掩码与运算计算相关地址 知道IP地址和子网掩码后可以算出 网络地址 广播地址 地址范围 本网有几台主机 例一:下面例子IP地址为192.168.100.5 子网掩码是255.255. ...

  5. Smarty 模板布局继承

    Smarty 模板继承 在覆盖父模板的{block}块以外的地方, 子模板不能定义任何内容.任何在{block}以外的 内容都会被自动忽略. 在子模板和父模板中的{block}内容,可以通过 appe ...

  6. VS2010/MFC编程入门之十(对话框:设置对话框控件的Tab顺序)

    前面几节鸡啄米为大家演示了加法计算器程序完整的编写过程,本节主要讲对话框上控件的Tab顺序如何调整. 上一讲为“计算”按钮添加了消息处理函数后,加法计算器已经能够进行浮点数的加法运算.但是还有个遗留的 ...

  7. SQL 处理排序空值

    ①oracle默认排序空值在后面 如果想要排序空值在前面可用关键字 NULLS FIRST, 排序空值在后面也有关键字NULLS LAST ②sqlserver默认排序空值在前面 如果想要排序时空值在 ...

  8. 2018-2019-1 20189215 《Linux内核原理与分析》第四周作业

    <庖丁解牛>第三章书本知识总结 计算机的三大法宝 存储程序计算机 函数调用堆栈 中断 操作系统的两把宝剑 中断上下文的切换--保存现场和恢复现场 进程上下文的切换 Linux内核源码的目录 ...

  9. luogu P1192 台阶问题

    https://www.luogu.org/problem/show?pid=1192 登楼梯 肯定能想到  dp[i] = dp[i-1] + dp[i-2] + ...+ dp[i-k] 然后想到 ...

  10. POJ 1386 Play on Words(欧拉路)

    http://poj.org/problem?id=1386 题意: 给出多个单词,只有单词首字母与上一个单子的末尾字母相同时可以连接,判断所有字母是否可以全部连接在一起. 思路: 判断是否存在欧拉道 ...