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. HDU5124:lines(线段树+离散化)或(离散化思想)

    http://acm.hdu.edu.cn/showproblem.php?pid=5124 Problem Description John has several lines. The lines ...

  2. java:判断二进制数据中第n位是否为1

    可以使用位运算来判断. &是位的与运算符,是指二进制数按位“与”的操作, 逻辑与就是两者都为真的时候才为真,其他真假,假真,假假的运算结果都是假.二进制写法如下 1 & 1 = 1 , ...

  3. xgboost 自定义评价函数(metric)与目标函数

    比赛得分公式如下: 其中,P为Precision , R为 Recall. GBDT训练基于验证集评价,此时会调用评价函数,XGBoost的best_iteration和best_score均是基于评 ...

  4. uva1292 树形dp

    这题说的是给了一个n个节点的一棵树,然后 你 从 这 棵 树 的 n 个 节点中 选择 尽量少的 点使得 每条边都至少有一个 士兵看守 dp[0][i]+=dp[1][j] dp[1][i]+=min ...

  5. 蜻蜓FM下载文件名还原

    从蜻蜓FM手机版可以下载音频文件,目的是可以使用普通的播放器进行音频的播放(只是缓存,还用蜻蜓fm播放的请路过),但问题来了,下载下来的音频文件不是在界面中我们看到的文件名称了.于是,我们要进行一项非 ...

  6. 一个Golang例子:for + goroutine + channel

    Rob Pike 在 Google I/O 2012 - Go Concurrency Patterns 里演示了一个例子(daisy chain). 视频地址:https://www.youtube ...

  7. 高级Bash脚本编程(二)

    高级Bash脚本编程(二) 退出 退出状态码 退出:exit 被用来结束一个脚本,它也返回一个值,并且这个值会传递给脚本的父进程,父进程会使用这个值做下一步的处理. 每个命令都会返回一个退出状态码,成 ...

  8. 20145325张梓靖 实验一 "Java开发环境的熟悉"

    20145325张梓靖 实验一 "Java开发环境的熟悉" 程序设计过程 实验内容 实现凯撒密码,并进行测试 编写代码 使用java.util.Scanner进行输入,而它的方法里 ...

  9. linux内核启动时报错ubi0 error: validate_ec_hdr: bad VID header offset 256, expected 64

    1.详细错误报告如下: ubi0 error: validate_ec_hdr: bad VID header offset 256, expected 64 ubi0 error: validate ...

  10. 什么是OPTEE-OS

    1. 为什么会出现这种技术? 为了安全,例如:保护指纹虹膜的生物特征数据 2. 为了确保数据安全各家公司都做了些什么? Arm公司提出的了trustzone技术,用一根安全总线(称为NS位)来判断当前 ...