PyAlgoTrade 0.20 中文文档(三)
工具
Quandl
pyalgotrade.tools.quandl.``build_feed
(sourceCode,tableCodes,fromYear,toYear,storage,frequency=86400,timezone=None,skipErrors=False,authToken=None,columnNames={},forceDownload=False,skipMalformedBars=False)
使用从 Quandl 下载的 CSV 文件构建和加载 pyalgotrade.barfeed.quandlfeed.Feed
。如果以前未下载过 CSV 文件,则会下载它们。
参数: |
---|
-
sourceCode(字符串.)- 数据集来源代码。
-
tableCodes(列表.)- 数据集表代码。
-
fromYear(整数.)- 第一年。
-
toYear(整数.)- 最后一年。
-
storage(字符串.)- 文件加载或下载的路径。
-
frequency – bars 的频率。仅支持 pyalgotrade.bar.Frequency.DAY 或 pyalgotrade.bar.Frequency.WEEK。
-
timezone(pytz 时区.)- 用于本地化 bars 的默认时区。请检查
pyalgotrade.marketsession
。 -
skipErrors(布尔值.)- 如果发生错误,继续加载/下载文件。
-
authToken(字符串.)- 可选。如果每天的调用次数超过 50 次,则需要身份验证令牌。
-
columnNames(字典.)-
可选。一个字典,用于映射列名。有效的键值为:
-
datetime
-
open
-
high
-
low
-
close
-
volume
-
adj_close
-
-
skipMalformedBars(布尔值.)- 如果在解析 bars 时出现错误,则为 True。
|
返回类型: | pyalgotrade.barfeed.quandlfeed.Feed 。 |
---|
pyalgotrade.tools.quandl.``download_daily_bars
(sourceCode,tableCode,year,csvFile,authToken=None)
从 Quandl 下载给定年份的每日 bars。
参数: |
---|
-
sourceCode(字符串.)- 数据集的来源代码。
-
tableCode(字符串.)- 数据集的表代码。
-
year(整数.)- 年份。
-
csvFile(字符串.)- 要写入的 CSV 文件的路径。
-
authToken(字符串.)- 可选。如果每天的调用次数超过 50 次,则需要身份验证令牌。
|
pyalgotrade.tools.quandl.``download_weekly_bars
(sourceCode,tableCode,year,csvFile,authToken=None)
从 Quandl 下载给定年份的每周 bars。
参数: |
---|
-
sourceCode(字符串.)- 数据集的来源代码。
-
tableCode(字符串.)- 数据集的表代码。
-
year(整数.)- 年份。
-
csvFile(字符串.)- 要写入的 CSV 文件的路径。
-
authToken(字符串.)- 可选。如果每天的调用次数超过 50 次,则需要身份验证令牌。
| ## BarFeed 重新采样
pyalgotrade.tools.resample.``resample_to_csv
(barFeed,frequency,csvFile)
将 BarFeed 重采样为 CSV 文件,按照一定频率对 bars 进行分组。生成的文件可以使用 pyalgotrade.barfeed.csvfeed.GenericBarFeed
进行加载。CSV 文件的格式如下:
Date Time,Open,High,Low,Close,Volume,Adj Close
2013-01-01 00:00:00,13.51001,13.56,13.51,13.56,273.88014126,13.51001
参数: |
---|
-
barFeed (
pyalgotrade.barfeed.BarFeed
) – 将提供数据的 bar feed。它应该只包含单个工具的数据。 -
frequency – 分组的频率,单位为秒。必须 > 0。
-
csvFile (字符串.) – 要写入的 CSV 文件路径。
|
注意
-
时间将不包含时区信息。
-
如果输入的 bar feed 没有该信息,则Adj Close 列可能为空。
-
支持的重采样频率包括:
-
少于 bar.Frequency.DAY
-
bar.Frequency.DAY
-
bar.Frequency.MONTH
-
目录
-
工具
-
Quandl
-
BarFeed 重采样
-
事件分析器
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/eventprofiler.html
灵感来源于QSTK,eventprofiler模块是一个工具,用于统计分析事件如何影响未来的股票价格。事件分析器扫描历史数据以寻找指定事件,然后计算该事件对过去和未来一定回溯期内的股票价格的影响。
该工具的目标是在继续回测流程之前帮助您快速验证一个想法。
类 pyalgotrade.eventprofiler.``Results
(eventsDict,lookBack,lookForward)
基类:object
分析器的结果。
getEventCount
()
返回发生的事件数量。跳过边界上的事件。
类 pyalgotrade.eventprofiler.``Predicate
基类:object
事件识别的基类。您应该子类化此类以实现事件识别逻辑。
eventOccurred
(instrument,bards)
覆盖(必需)以确定上一个数据条中是否发生了事件(bards[-1])。
参数: |
---|
-
instrument(字符串) – 仪器标识符。
-
bards(
pyalgotrade.dataseries.bards.BarDataSeries
.) – 给定仪器的 BarDataSeries。
|
返回类型: | 布尔值。 |
---|
类 pyalgotrade.eventprofiler.``Profiler
(predicate,lookBack,lookForward)
基类:object
该类负责扫描历史数据并分析事件之前和之后的回报。
参数: |
---|
-
predicate(
Predicate
.) – 负责识别事件的Predicate
子类。 -
lookBack(整数) – 事件前要分析的数据条数。必须 > 0。
-
lookForward(整数) – 事件后要分析的数据条数。必须 > 0。
|
getResults
()
返回分析结果。
返回类型: | Results . |
---|
run
(feed,useAdjustedCloseForReturns=True)
使用提供的数据条运行分析。
参数: |
---|
-
barFeed(
pyalgotrade.barfeed.BarFeed
。) – 用于运行分析的数据条。 -
useAdjustedCloseForReturns(布尔值) – 如果应使用调整后的收盘价计算回报,则为 True。
|
pyalgotrade.eventprofiler.``plot
(profilerResults)
绘制分析结果。
参数: | profilerResults(Results .) – 分析结果 |
---|
示例
以下示例受到 Ernie Chan 的书籍《Algorithmic Trading: Winning Strategies and Their Rationale》中的“买入跳空模型”的启发:
- 思路是选择在市场开盘附近的一只股票,其从前一日最低点到今日开盘的收益低于一个标准偏差。标准偏差是使用过去 90 天的每日收盘至收盘收益率计算的。这些是“跳空下跌”的股票。
- 这是通过要求开盘价高于收盘价的 20 日移动平均线来缩小范围的。
from __future__ import print_function
from pyalgotrade import eventprofiler
from pyalgotrade.technical import stats
from pyalgotrade.technical import roc
from pyalgotrade.technical import ma
from pyalgotrade.tools import quandl
# Event inspired on an example from Ernie Chan's book:
# 'Algorithmic Trading: Winning Strategies and Their Rationale'
class BuyOnGap(eventprofiler.Predicate):
def __init__(self, feed):
super(BuyOnGap, self).__init__()
stdDevPeriod = 90
smaPeriod = 20
self.__returns = {}
self.__stdDev = {}
self.__ma = {}
for instrument in feed.getRegisteredInstruments():
priceDS = feed[instrument].getAdjCloseDataSeries()
# Returns over the adjusted close values.
self.__returns[instrument] = roc.RateOfChange(priceDS, 1)
# StdDev over those returns.
self.__stdDev[instrument] = stats.StdDev(self.__returns[instrument], stdDevPeriod)
# MA over the adjusted close values.
self.__ma[instrument] = ma.SMA(priceDS, smaPeriod)
def __gappedDown(self, instrument, bards):
ret = False
if self.__stdDev[instrument][-1] is not None:
prevBar = bards[-2]
currBar = bards[-1]
low2OpenRet = (currBar.getOpen(True) - prevBar.getLow(True)) / float(prevBar.getLow(True))
if low2OpenRet < (self.__returns[instrument][-1] - self.__stdDev[instrument][-1]):
ret = True
return ret
def __aboveSMA(self, instrument, bards):
ret = False
if self.__ma[instrument][-1] is not None and bards[-1].getOpen(True) > self.__ma[instrument][-1]:
ret = True
return ret
def eventOccurred(self, instrument, bards):
ret = False
if self.__gappedDown(instrument, bards) and self.__aboveSMA(instrument, bards):
ret = True
return ret
def main(plot):
instruments = ["IBM", "AES", "AIG"]
feed = quandl.build_feed("WIKI", instruments, 2008, 2009, ".")
predicate = BuyOnGap(feed)
eventProfiler = eventprofiler.Profiler(predicate, 5, 5)
eventProfiler.run(feed, True)
results = eventProfiler.getResults()
print("%d events found" % (results.getEventCount()))
if plot:
eventprofiler.plot(results)
if __name__ == "__main__":
main(True)
代码正在做 4 件事情:
- 声明一个
Predicate
,实现“买入跳空模型”事件识别。- 为某些股票加载进度条。
- 运行分析。
- 绘制结果。
输出应如下所示:
2017-07-22 00:26:06,574 quandl [INFO] Downloading IBM 2008 to ./WIKI-IBM-2008-quandl.csv
2017-07-22 00:26:08,299 quandl [INFO] Downloading AES 2008 to ./WIKI-AES-2008-quandl.csv
2017-07-22 00:26:09,849 quandl [INFO] Downloading AIG 2008 to ./WIKI-AIG-2008-quandl.csv
2017-07-22 00:26:11,513 quandl [INFO] Downloading IBM 2009 to ./WIKI-IBM-2009-quandl.csv
2017-07-22 00:26:13,128 quandl [INFO] Downloading AES 2009 to ./WIKI-AES-2009-quandl.csv
2017-07-22 00:26:14,626 quandl [INFO] Downloading AIG 2009 to ./WIKI-AIG-2009-quandl.csv
15 events found
请注意累积收益已归一化至事件发生时间。
目录
-
事件分析器
- 示例
比特币
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/bitcoin.html
内容:
-
Bitstamp 支持
-
bitstamp – Bitstamp 参考
-
Bitstamp 示例
-
-
比特币图表支持
-
bitcoincharts – 比特币图表参考
-
比特币图表示例
-
Bitstamp 支持
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/bitstamp.html
bitstamp 包通过 Bitstamp(www.bitstamp.net/
)为纸上交易和实时交易比特币策略提供支持。
Bitstamp 支持依赖于:
-
tornado (
www.tornadoweb.org/en/stable/
)
因此,在继续之前,请确保已安装它们。
目录:
-
bitstamp – Bitstamp 参考
-
WebSocket
-
源
-
经纪人
-
-
Bitstamp 示例
bitstamp – Bitstamp 参考
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/bitstamp_ref.html
WebSocket
此包包含由 Bitstamp 的流媒体服务发出的事件的类。有关更多信息,请查看www.bitstamp.net/websocket/
。
类 pyalgotrade.bitstamp.wsclient.``OrderBookUpdate
(dateTime, eventDict)
基类:pyalgotrade.websocket.pusher.Event
一个订单簿更新事件。
getAskPrices
()
返回一个包含前 20 个卖价的列表。
getAskVolumes
()
返回一个包含前 20 个卖量的列表。
getBidPrices
()
返回一个包含前 20 个买价的列表。
getBidVolumes
()
返回一个包含前 20 个买量的列表。
getDateTime
()
返回此事件被接收的datetime.datetime
。
类 pyalgotrade.bitstamp.wsclient.``Trade
(dateTime, eventDict)
基类:pyalgotrade.websocket.pusher.Event
一个交易事件。
getAmount
()
返回交易金额。
getDateTime
()
返回此事件被接收的datetime.datetime
。
getId
()
返回交易 ID。
getPrice
()
返回交易价格。
isBuy
()
如果交易是买入,则返回 True。
isSell
()
如果交易是卖出,则返回 True。
类 pyalgotrade.bitstamp.wsclient.``WebSocketClient
(queue)
基类:pyalgotrade.websocket.pusher.WebSocketClient
此 websocket 客户端类设计为在单独的线程中运行,因此事件被推送到队列中。
类 pyalgotrade.bitstamp.wsclient.``WebSocketClientThread
基类:pyalgotrade.websocket.client.WebSocketClientThreadBase
此线程类负责运行 WebSocketClient。 ## 数据源
类 pyalgotrade.bitstamp.barfeed.``LiveTradeFeed
(maxLen=None)
基类:pyalgotrade.barfeed.BaseBarFeed
从实时交易构建条形图的实时 BarFeed。
参数: | maxLen (int.) – pyalgotrade.dataseries.bards.BarDataSeries 将保存的值的最大数量。一旦有界长度已满,当添加新项时,相应数量的项将从相反的一端丢弃。如果为 None,则使用 dataseries.DEFAULT_MAX_LEN。 |
---|
注意
请注意,每笔交易都将创建一个 Bar,因此开盘价、最高价、最低价和收盘价将全部相同。
getOrderBookUpdateEvent
()
返回当订单簿更新时将发出的事件。
事件处理程序应接收一个参数:
- 一个
pyalgotrade.bitstamp.wsclient.OrderBookUpdate
实例。
| 返回类型: | pyalgotrade.observer.Event
。 | ## 经纪商
类 pyalgotrade.bitstamp.broker.``PaperTradingBroker
(cash, barFeed, fee=0.0025)
Bases: pyalgotrade.bitstamp.broker.BacktestingBroker
Bitstamp 模拟交易经纪人。
参数: |
---|
-
cash (int/float.) – 初始现金金额。
-
barFeed (
pyalgotrade.barfeed.BarFeed
) – 提供 K 线图的数据源。 -
fee (float.) – 每笔订单的手续费百分比。默认为 0.5%。
|
注意
-
仅支持限价订单。
-
订单自动设置为goodTillCanceled=True和allOrNone=False。
-
BUY_TO_COVER 订单映射到 BUY 订单。
-
SELL_SHORT 订单映射到 SELL 订单。
class pyalgotrade.bitstamp.broker.``LiveBroker
(clientId, key, secret)
Bases: pyalgotrade.broker.Broker
Bitstamp 实时交易经纪人。
参数: |
---|
-
clientId (string.) – 客户端 ID。
-
key (string.) – API 密钥。
-
secret (string.) – API 密钥。
|
注意
-
仅支持限价订单。
-
订单自动设置为goodTillCanceled=True和allOrNone=False。
-
BUY_TO_COVER 订单映射到 BUY 订单。
-
SELL_SHORT 订单映射到 SELL 订单。
-
API 访问权限应包括:
-
账户余额
-
挂单
-
买入限价单
-
用户交易
-
取消订单
-
卖出限价单
-
refreshAccountBalance
()
刷新现金和 BTC 余额。
目录
-
bitstamp – Bitstamp 参考
-
WebSocket
-
数据源
-
经纪人
-
前一个主题
Bitstamp 支持
下一个主题
Bitstamp 示例
本页
- 显示源代码
快速搜索
输入搜索词或模块、类或函数名。
导航
-
索引
-
模块 |
-
下一页 |
-
上一页 |
-
PyAlgoTrade 0.20 文档 »
-
比特币 »
-
Bitstamp 支持 »
Bitstamp 示例
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/bitstamp_example.html
这个简单的 SMA 交叉示例的目标是展示如何将所有要素组合在一起,利用 Bitstamp 提供的实时数据源进行模拟交易策略(www.bitstamp.net/
)。
这个示例假设您已经熟悉了教程部分提出的基本概念。
需要强调的关键点是:
- 我们使用
pyalgotrade.strategy.BaseStrategy
作为基类,而不是pyalgotrade.strategy.BacktestingStrategy
。这不是一次回测。- 交易事件通过调用onBars来通知。无需手动订阅。
- 订单簿更新事件通过手动订阅
pyalgotrade.bitstamp.barfeed.LiveTradeFeed.getOrderBookUpdateEvent
来处理。这是为了与最新的买入和卖出价格保持同步所需的。
from pyalgotrade.bitstamp import barfeed
from pyalgotrade.bitstamp import broker
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
class Strategy(strategy.BaseStrategy):
def __init__(self, feed, brk):
super(Strategy, self).__init__(feed, brk)
smaPeriod = 20
self.__instrument = "BTC"
self.__prices = feed[self.__instrument].getCloseDataSeries()
self.__sma = ma.SMA(self.__prices, smaPeriod)
self.__bid = None
self.__ask = None
self.__position = None
self.__posSize = 0.05
# Subscribe to order book update events to get bid/ask prices to trade.
feed.getOrderBookUpdateEvent().subscribe(self.__onOrderBookUpdate)
def __onOrderBookUpdate(self, orderBookUpdate):
bid = orderBookUpdate.getBidPrices()[0]
ask = orderBookUpdate.getAskPrices()[0]
if bid != self.__bid or ask != self.__ask:
self.__bid = bid
self.__ask = ask
self.info("Order book updated. Best bid: %s. Best ask: %s" % (self.__bid, self.__ask))
def onEnterOk(self, position):
self.info("Position opened at %s" % (position.getEntryOrder().getExecutionInfo().getPrice()))
def onEnterCanceled(self, position):
self.info("Position entry canceled")
self.__position = None
def onExitOk(self, position):
self.__position = None
self.info("Position closed at %s" % (position.getExitOrder().getExecutionInfo().getPrice()))
def onExitCanceled(self, position):
# If the exit was canceled, re-submit it.
self.__position.exitLimit(self.__bid)
def onBars(self, bars):
bar = bars[self.__instrument]
self.info("Price: %s. Volume: %s." % (bar.getClose(), bar.getVolume()))
# Wait until we get the current bid/ask prices.
if self.__ask is None:
return
# 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:
self.info("Entry signal. Buy at %s" % (self.__ask))
self.__position = self.enterLongLimit(self.__instrument, self.__ask, self.__posSize, True)
# Check if we have to close the position.
elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
self.info("Exit signal. Sell at %s" % (self.__bid))
self.__position.exitLimit(self.__bid)
def main():
barFeed = barfeed.LiveTradeFeed()
brk = broker.PaperTradingBroker(1000, barFeed)
strat = Strategy(barFeed, brk)
strat.run()
if __name__ == "__main__":
main()
输出应该如下所示:
2014-03-15 00:35:59,085 bitstamp [INFO] Initializing websocket client.
2014-03-15 00:35:59,452 bitstamp [INFO] Connection established.
2014-03-15 00:35:59,453 bitstamp [INFO] Initialization ok.
2014-03-15 00:36:30,726 strategy [INFO] Order book updated. Best bid: 629.6\. Best ask: 630.0
2014-03-15 00:39:04,829 strategy [INFO] Order book updated. Best bid: 628.89\. Best ask: 630.0
2014-03-15 00:44:18,845 strategy [INFO] Price: 630.0\. Volume: 0.01.
2014-03-15 00:44:18,894 strategy [INFO] Order book updated. Best bid: 630.0\. Best ask: 631.49
2014-03-15 00:44:29,719 strategy [INFO] Price: 630.0\. Volume: 0.02.
2014-03-15 00:44:59,861 strategy [INFO] Price: 631.49\. Volume: 0.03360823.
2014-03-15 00:45:37,425 strategy [INFO] Order book updated. Best bid: 630.0\. Best ask: 631.6
2014-03-15 00:45:39,848 strategy [INFO] Price: 631.6\. Volume: 3.35089782.
2014-03-15 00:45:39,918 strategy [INFO] Price: 632.24\. Volume: 0.136.
2014-03-15 00:45:39,971 strategy [INFO] Price: 632.24\. Volume: 0.138.
2014-03-15 00:45:40,057 strategy [INFO] Price: 632.25\. Volume: 0.09076537.
2014-03-15 00:45:40,104 strategy [INFO] Price: 632.42\. Volume: 0.74011681.
2014-03-15 00:45:40,205 strategy [INFO] Order book updated. Best bid: 630.0\. Best ask: 632.42
2014-03-15 00:48:30,005 strategy [INFO] Price: 630.0\. Volume: 4.97.
2014-03-15 00:48:30,039 strategy [INFO] Price: 629.6\. Volume: 0.09.
2014-03-15 00:48:30,121 strategy [INFO] Price: 629.54\. Volume: 0.09.
.
.
.
2014-03-15 00:48:33,053 strategy [INFO] Price: 625.55\. Volume: 1.296299.
2014-03-15 00:48:33,164 strategy [INFO] Price: 625.52\. Volume: 0.0924981.
2014-03-15 00:48:33,588 strategy [INFO] Price: 625.45\. Volume: 13.46260589.
2014-03-15 00:48:33,635 strategy [INFO] Order book updated. Best bid: 629.26\. Best ask: 632.42
2014-03-15 00:48:33,727 strategy [INFO] Price: 625.45\. Volume: 1.75.
2014-03-15 00:48:34,261 strategy [INFO] Price: 625.48\. Volume: 0.1.
2014-03-15 00:48:34,908 strategy [INFO] Order book updated. Best bid: 629.26\. Best ask: 631.39
2014-03-15 00:48:36,203 strategy [INFO] Order book updated. Best bid: 629.26\. Best ask: 632.42
.
.
.
2014-03-15 00:49:01,945 strategy [INFO] Order book updated. Best bid: 629.26\. Best ask: 631.39
2014-03-15 00:49:34,743 strategy [INFO] Order book updated. Best bid: 629.26\. Best ask: 631.28
2014-03-15 00:49:57,651 strategy [INFO] Price: 629.26\. Volume: 0.66893865.
2014-03-15 00:49:57,651 strategy [INFO] Entry signal. Buy at 631.28
2014-03-15 00:50:09,934 strategy [INFO] Order book updated. Best bid: 629.26\. Best ask: 631.39
2014-03-15 00:50:20,786 strategy [INFO] Order book updated. Best bid: 627.02\. Best ask: 631.39
2014-03-15 00:50:25,658 strategy [INFO] Price: 631.39\. Volume: 0.01.
2014-03-15 00:50:25,732 strategy [INFO] Price: 631.39\. Volume: 0.01.
2014-03-15 00:50:25,791 strategy [INFO] Price: 631.93\. Volume: 0.5.
2014-03-15 00:50:25,847 strategy [INFO] Price: 632.42\. Volume: 0.25988319.
2014-03-15 00:50:25,900 strategy [INFO] Price: 632.42\. Volume: 0.184.
2014-03-15 00:50:25,952 strategy [INFO] Price: 632.42\. Volume: 0.184.
2014-03-15 00:50:26,000 strategy [INFO] Price: 632.42\. Volume: 0.184.
2014-03-15 00:50:26,065 strategy [INFO] Price: 632.44\. Volume: 0.184.
2014-03-15 00:50:26,139 strategy [INFO] Price: 632.97\. Volume: 0.092.
2014-03-15 00:50:26,300 strategy [INFO] Order book updated. Best bid: 627.02\. Best ask: 629.0
2014-03-15 00:50:26,398 strategy [INFO] Price: 633.1\. Volume: 0.16211681.
2014-03-15 00:50:29,850 strategy [INFO] Position opened at 629.0
2014-03-15 00:50:29,850 strategy [INFO] Price: 629.0\. Volume: 0.25152623.
2014-03-15 00:50:29,850 strategy [INFO] Exit signal. Sell at 627.02
2014-03-15 00:50:37,294 strategy [INFO] Order book updated. Best bid: 627.02\. Best ask: 633.1
2014-03-15 00:50:43,526 strategy [INFO] Order book updated. Best bid: 627.02\. Best ask: 633.08
2014-03-15 00:51:07,604 strategy [INFO] Order book updated. Best bid: 627.02\. Best ask: 632.99
2014-03-15 00:51:46,194 strategy [INFO] Order book updated. Best bid: 627.02\. Best ask: 630.89
2014-03-15 00:52:08,223 strategy [INFO] Position closed at 627.02
2014-03-15 00:52:08,223 strategy [INFO] Price: 627.02\. Volume: 0.0924979.
2014-03-15 00:52:08,290 strategy [INFO] Price: 627.02\. Volume: 0.02.
2014-03-15 00:52:08,530 strategy [INFO] Order book updated. Best bid: 627.01\. Best ask: 627.02
2014-03-15 00:52:35,347 strategy [INFO] Price: 630.89\. Volume: 0.07.
2014-03-15 00:52:35,347 strategy [INFO] Entry signal. Buy at 627.02
2014-03-15 00:52:35,348 strategy [INFO] Price: 630.95\. Volume: 0.09.
2014-03-15 00:52:35,428 strategy [INFO] Price: 631.0\. Volume: 0.05.
.
.
.
2014-03-15 00:54:14,077 strategy [INFO] Order book updated. Best bid: 628.81\. Best ask: 632.4
2014-03-15 00:54:21,084 strategy [INFO] Order book updated. Best bid: 631.0\. Best ask: 632.4
2014-03-15 00:54:34,484 strategy [INFO] Price: 632.4\. Volume: 0.296299.
2014-03-15 00:54:34,484 strategy [INFO] Exit signal. Sell at 631.0
2014-03-15 00:54:34,484 strategy [INFO] Position entry canceled
2014-03-15 00:54:34,578 strategy [INFO] Price: 632.45\. Volume: 3.5.
2014-03-15 00:54:34,642 strategy [INFO] Price: 632.45\. Volume: 0.5715.
2014-03-15 00:54:34,708 strategy [INFO] Price: 632.46\. Volume: 0.136.
2014-03-15 00:54:34,789 strategy [INFO] Price: 632.46\. Volume: 1.2682.
2014-03-15 00:54:34,885 strategy [INFO] Price: 632.46\. Volume: 3.5.
2014-03-15 00:54:34,949 strategy [INFO] Price: 632.46\. Volume: 5.25.
2014-03-15 00:54:35,029 strategy [INFO] Price: 632.47\. Volume: 9.88740834.
2014-03-15 00:54:35,165 strategy [INFO] Price: 632.89\. Volume: 18.24259574.
2014-03-15 00:54:35,165 strategy [INFO] Entry signal. Buy at 632.4
2014-03-15 00:54:35,286 strategy [INFO] Price: 633.0\. Volume: 0.092.
2014-03-15 00:54:35,357 strategy [INFO] Price: 633.1\. Volume: 0.37612853.
.
.
.
2014-03-15 00:56:48,885 strategy [INFO] Order book updated. Best bid: 632.1\. Best ask: 634.35
2014-03-15 00:56:57,234 strategy [INFO] Position opened at 632.1
2014-03-15 00:56:57,235 strategy [INFO] Price: 632.1\. Volume: 0.66267992.
2014-03-15 00:56:57,235 strategy [INFO] Exit signal. Sell at 632.1
2014-03-15 00:56:57,268 strategy [INFO] Price: 631.83\. Volume: 59.33732008.
2014-03-15 00:56:57,356 strategy [INFO] Order book updated. Best bid: 631.83\. Best ask: 634.35
2014-03-15 00:57:03,528 strategy [INFO] Price: 631.83\. Volume: 0.08267992.
2014-03-15 00:57:03,604 strategy [INFO] Order book updated. Best bid: 631.0\. Best ask: 631.83
2014-03-15 00:57:04,824 strategy [INFO] Order book updated. Best bid: 631.0\. Best ask: 634.34
2014-03-15 00:57:09,775 strategy [INFO] Order book updated. Best bid: 631.0\. Best ask: 634.33
2014-03-15 00:57:11,112 strategy [INFO] Order book updated. Best bid: 632.1\. Best ask: 634.33
2014-03-15 00:57:15,822 strategy [INFO] Position closed at 632.1
2014-03-15 00:57:15,822 strategy [INFO] Price: 632.1\. Volume: 0.2.
2014-03-15 00:57:20,839 strategy [INFO] Price: 632.1\. Volume: 0.46267992.
2014-03-15 00:57:22,065 strategy [INFO] Price: 631.2\. Volume: 0.03732008.
2014-03-15 00:57:22,122 strategy [INFO] Price: 634.33\. Volume: 0.135.
2014-03-15 00:57:22,122 strategy [INFO] Entry signal. Buy at 634.33
2014-03-15 00:57:22,184 strategy [INFO] Price: 634.34\. Volume: 0.97972409.
.
.
.
为了实时交易这个策略,你应该使用pyalgotrade.bitstamp.broker.LiveBroker
而不是pyalgotrade.bitstamp.broker.PaperTradingBroker
。
请注意,如果您尝试实时交易此策略,您可能会损失金钱。 在进行实时交易之前,请务必编写您自己的策略,进行彻底的回测和模拟交易,然后再冒险使用真实资金。
Bitcoin 图表支持
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/bitcoincharts.html
bitcoincharts 包增加了对由 www.bitcoincharts.com/
提供的历史交易数据与比特币策略回测的支持。
历史交易数据以 CSV 格式描述,详情请见 www.bitcoincharts.com/about/markets-api/
,文件可从 api.bitcoincharts.com/v1/csv/
下载。
目录:
-
bitcoincharts – Bitcoin 图表参考
- Feeds
-
Bitcoin 图表示例
bitcoincharts – Bitcoin Charts 参考
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/bitcoincharts_ref.html
饲料
类 pyalgotrade.bitcoincharts.barfeed.``CSVTradeFeed
(时区=None, maxLen=None)
基类: pyalgotrade.barfeed.csvfeed.BarFeed
一个从历史交易数据 CSV 文件构建条形图的 BarFeed,如www.bitcoincharts.com/about/markets-api/
所述。文件可从api.bitcoincharts.com/v1/csv/
下载。
参数: |
---|
-
时区 (A pytz 时区.) – 一个可选的默认时区,用于本地化条形图。默认情况下,条形图以 UTC 加载。
-
maxLen (整数.) –
pyalgotrade.dataseries.bards.BarDataSeries
将保存的值的最大数量。如果不是 None,则必须大于 0。一旦有界长度已满,当添加新项时,相应数量的项将从相反的一端丢弃。如果为 None,则使用 dataseries.DEFAULT_MAX_LEN。
|
注意
-
对于每一笔交易,都会创建一个
pyalgotrade.bar.Bar
实例,因此开盘价、最高价、最低价和收盘价都相同。 -
文件必须按升序排列unixtime列。
addBarsFromCSV
(路径, instrument='BTC', 时区=None, fromDateTime=None, toDateTime=None)
从交易 CSV 格式的文件加载条形图。
参数: |
---|
-
路径 (字符串.) – 文件的路径。
-
instrument (字符串.) – 仪器标识符。
-
时区 (A pytz 时区.) – 一个可选的用于本地化条形图的时区。默认情况下,条形图以 UTC 加载。
-
fromDateTime (datetime.datetime.) – 一个可选的日期时间,用于过滤要加载的条形图。如果提供,则只加载其日期时间大于或等于 fromDateTime 的那些条。
-
toDateTime (datetime.datetime.) – 一个可选的日期时间,用于过滤要加载的条形图。如果提供,则只加载其日期时间低于或等于 toDateTime 的那些条。
|
注意
-
您从中加载条形图的每个文件必须具有相同货币的交易。
-
如果 fromDateTime 或 toDateTime 是幼稚的,则将其视为 UTC。
目录
-
bitcoincharts – Bitcoin Charts 参考
- Feeds
比特币图表示例
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/bitcoincharts_example.html
尽管使用www.bitcoincharts.com/about/markets-api/
提供的刻度数据可以完全进行策略回测,使用pyalgotrade.bitcoincharts.barfeed.CSVTradeFeed
,但您可能希望使用不同频率的汇总柱状图进行回测,以加快回测速度。
截至 2014 年 8 月 12 日,api.bitcoincharts.com/v1/csv/bitstampUSD.csv.gz
有 4588830 个事件,因此我们将使用以下脚本将其中的一部分转换为 30 分钟的柱状图,用于回测目的:
from pyalgotrade.bitcoincharts import barfeed
from pyalgotrade.tools import resample
from pyalgotrade import bar
import datetime
def main():
barFeed = barfeed.CSVTradeFeed()
barFeed.addBarsFromCSV("bitstampUSD.csv", fromDateTime=datetime.datetime(2014, 1, 1))
resample.resample_to_csv(barFeed, bar.Frequency.MINUTE*30, "30min-bitstampUSD.csv")
if __name__ == "__main__":
main()
执行需要一些时间,所以请耐心等待。重新采样后的文件应该是这样的:
Date Time,Open,High,Low,Close,Volume,Adj Close
2014-01-01 00:00:00,732.0,738.25,729.01,734.81,266.17955488,
2014-01-01 00:30:00,734.81,739.9,734.47,739.02,308.96802502,
2014-01-01 01:00:00,739.02,739.97,737.65,738.11,65.66924473,
2014-01-01 01:30:00,738.0,742.0,737.65,741.89,710.27165024,
2014-01-01 02:00:00,741.89,757.99,741.89,752.23,1085.13335011,
2014-01-01 02:30:00,752.23,755.0,747.0,747.2,272.03949342,
2014-01-01 04:00:00,744.98,748.02,744.98,747.19,104.65989075,
.
.
现在我们可以利用pyalgotrade.barfeed.csvfeed.GenericBarFeed
来加载重新采样后的文件,并回测比特币策略。我们将使用 VWAP 动量策略进行说明:
from pyalgotrade import bar
from pyalgotrade import strategy
from pyalgotrade import plotter
from pyalgotrade.technical import vwap
from pyalgotrade.barfeed import csvfeed
from pyalgotrade.bitstamp import broker
from pyalgotrade import broker as basebroker
class VWAPMomentum(strategy.BacktestingStrategy):
MIN_TRADE = 5
def __init__(self, feed, brk, instrument, vwapWindowSize, buyThreshold, sellThreshold):
super(VWAPMomentum, self).__init__(feed, brk)
self.__instrument = instrument
self.__vwap = vwap.VWAP(feed[instrument], vwapWindowSize)
self.__buyThreshold = buyThreshold
self.__sellThreshold = sellThreshold
def _getActiveOrders(self):
orders = self.getBroker().getActiveOrders()
buy = [o for o in orders if o.isBuy()]
sell = [o for o in orders if o.isSell()]
return buy, sell
def _cancelOrders(self, orders):
brk = self.getBroker()
for o in orders:
self.info("Canceling order %s" % (o.getId()))
brk.cancelOrder(o)
def _buySignal(self, price):
buyOrders, sellOrders = self._getActiveOrders()
self._cancelOrders(sellOrders)
brk = self.getBroker()
cashAvail = brk.getCash() * 0.98
size = round(cashAvail / price, 3)
if len(buyOrders) == 0 and price*size > VWAPMomentum.MIN_TRADE:
self.info("Buy %s at %s" % (size, price))
try:
self.limitOrder(self.__instrument, price, size)
except Exception as e:
self.error("Failed to buy: %s" % (e))
def _sellSignal(self, price):
buyOrders, sellOrders = self._getActiveOrders()
self._cancelOrders(buyOrders)
brk = self.getBroker()
shares = brk.getShares(self.__instrument)
if len(sellOrders) == 0 and shares > 0:
self.info("Sell %s at %s" % (shares, price))
self.limitOrder(self.__instrument, price, shares*-1)
def getVWAP(self):
return self.__vwap
def onBars(self, bars):
vwap = self.__vwap[-1]
if vwap is None:
return
price = bars[self.__instrument].getClose()
if price > vwap * (1 + self.__buyThreshold):
self._buySignal(price)
elif price < vwap * (1 - self.__sellThreshold):
self._sellSignal(price)
def onOrderUpdated(self, order):
if order.isBuy():
orderType = "Buy"
else:
orderType = "Sell"
exec_info_str = ""
if order.getExecutionInfo():
exec_info_str = " - Price: %s - Amount: %s - Fee: %s" % (
order.getExecutionInfo().getPrice(), order.getExecutionInfo().getQuantity(),
round(order.getExecutionInfo().getCommission(), 2)
)
self.info("%s order %d updated - Status: %s%s" % (
orderType,
order.getId(),
basebroker.Order.State.toString(order.getState()),
exec_info_str
))
def main(plot):
instrument = "BTC"
initialCash = 1000
vwapWindowSize = 100
buyThreshold = 0.02
sellThreshold = 0.01
barFeed = csvfeed.GenericBarFeed(bar.Frequency.MINUTE*30)
barFeed.addBarsFromCSV(instrument, "30min-bitstampUSD.csv")
brk = broker.BacktestingBroker(initialCash, barFeed)
strat = VWAPMomentum(barFeed, brk, instrument, vwapWindowSize, buyThreshold, sellThreshold)
if plot:
plt = plotter.StrategyPlotter(strat)
plt.getInstrumentSubplot(instrument).addDataSeries("VWAP", strat.getVWAP())
strat.run()
if plot:
plt.plot()
if __name__ == "__main__":
main(True)
这是绘图的样子:
Twitter 支持
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/twitter.html
Twitter 包添加了对在您的策略中接收 Twitter 事件并将其纳入您的交易决策中的支持。请注意,由于这是一个实时数据源,因此仅在模拟交易或实际交易场景中才有意义,而不适用于回测。
Twitter 支持依赖于tweepy (github.com/tweepy/tweepy
),所以在继续之前确保已安装。
目录:
-
twitter – Twitter feed reference
- Feed
-
Twitter 示例
twitter – Twitter feed reference
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/twitter_ref.html
Feed
类 pyalgotrade.twitter.feed.``TwitterFeed
(consumerKey, consumerSecret, accessToken, accessTokenSecret, track=[], follow=[], languages=[])
基类: pyalgotrade.observer.Subject
负责连接到 Twitter 的公共流 API 并分发事件的类。有关更多信息,请查看dev.twitter.com/docs/streaming-apis/streams/public
。
参数: |
---|
-
consumerKey (字符串.) – 消费者密钥。
-
consumerSecret (字符串.) – 消费者密钥。
-
accessToken (字符串.) – 访问令牌。
-
accessTokenSecret (字符串.) – 访问令牌密钥。
-
track (列表.) – 用于确定将在流上发布哪些推文的短语列表。一个短语可以是一个或多个由空格分隔的术语,并且如果短语中的所有术语都出现在推文中,则匹配短语,无论顺序如何并且忽略大小写。
-
follow (列表.) – 一个用户 ID 列表,表示应该在流上发布推文的用户。不支持关注受保护的用户。
-
languages (列表.) – 语言 ID 列表,定义在
tools.ietf.org/html/bcp47
中。
|
注
-
转到
dev.twitter.com
并创建一个应用程序。之后,消费者密钥和密钥将为您生成。 -
在“您的访问令牌”部分创建一个访问令牌。
-
至少track或follow必须设置。
subscribe
(回调)
订阅 Twitter 事件。事件处理程序将接收一个与dev.twitter.com/docs/streaming-apis/messages#Public_stream_messages
中定义的数据相符的字典。
目录
-
twitter – Twitter feed reference
- Feed
Twitter 示例
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/twitter_example.html
这个简单示例的目标是向你展示如何将所有部分组合起来,将 Twitter 事件纳入策略中。我们将使用 Bitstamp 的实时反馈,因为不支持使用 Twitter 进行回测,请在继续之前查看Bitstamp 示例 部分。
要连接到 Twitter 的 API,您需要:
-
使用者密钥
-
使用者密钥
-
访问令牌
-
访问令牌密钥
转到 dev.twitter.com
并创建一个应用程序。然后,会为您生成使用者密钥和密钥。然后,您需要在“您的访问令牌”部分下创建一个访问令牌。
强调的关键点是:
- 我们使用
pyalgotrade.strategy.BaseStrategy
而不是pyalgotrade.strategy.BacktestingStrategy
作为基类。这不是一次回测。- 在运行策略之前,必须将
pyalgotrade.twitter.feed.TwitterFeed
实例包含在策略事件分派循环中。
from pyalgotrade import strategy
from pyalgotrade.bitstamp import barfeed
from pyalgotrade.bitstamp import broker
from pyalgotrade.twitter import feed as twitterfeed
class Strategy(strategy.BaseStrategy):
def __init__(self, feed, brk, twitterFeed):
super(Strategy, self).__init__(feed, brk)
self.__instrument = "BTC"
# Subscribe to Twitter events.
twitterFeed.subscribe(self.__onTweet)
def __onTweet(self, data):
# Refer to https://dev.twitter.com/docs/streaming-apis/messages#Public_stream_messages for
# the information available in data.
try:
self.info("Twitter: %s" % (data["text"]))
except KeyError:
pass
def onBars(self, bars):
bar = bars[self.__instrument]
self.info("Price: %s. Volume: %s." % (bar.getClose(), bar.getVolume()))
def main():
# Go to http://dev.twitter.com and create an app.
# The consumer key and secret will be generated for you after that.
consumer_key = "<YOUR-CONSUMER-KEY-HERE>"
consumer_secret = "<YOUR-CONSUMER-SECRET-HERE>"
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token = "<YOUR-ACCESS-TOKEN-HERE>"
access_token_secret = "<YOUR-ACCESS-TOKEN-SECRET-HERE>"
# Create a twitter feed to track BitCoin related events.
track = ["bitcoin", "btc", "mtgox", "bitstamp", "xapo"]
follow = []
languages = ["en"]
twitterFeed = twitterfeed.TwitterFeed(consumer_key, consumer_secret, access_token, access_token_secret, track, follow, languages)
barFeed = barfeed.LiveTradeFeed()
brk = broker.PaperTradingBroker(1000, barFeed)
strat = Strategy(barFeed, brk, twitterFeed)
# It is VERY important to add twitterFeed to the event dispatch loop before running the strategy.
strat.getDispatcher().addSubject(twitterFeed)
strat.run()
if __name__ == "__main__":
main()
输出应如下所示:
2014-03-15 02:42:07,696 bitstamp [INFO] Initializing client.
2014-03-15 02:42:08,174 bitstamp [INFO] Connection established.
2014-03-15 02:42:08,175 bitstamp [INFO] Initialization ok.
2014-03-15 02:42:08,175 twitter [INFO] Initializing client.
2014-03-15 02:42:09,238 twitter [INFO] Connected.
2014-03-15 02:42:15,107 strategy [INFO] Twitter: Warren Buffett Urges Investors to ‘Stay Away’ from Bitcoin http://t.co/WWRCr3rfob
2014-03-15 02:42:22,926 strategy [INFO] Twitter: FundingUnion Inc. Bitcoin MLM Social Build - The Currently in BETA version - Join Today : http://t.co/bxcfoBV0I4 #Bitcoin #MLM #SocialMedia
2014-03-15 02:42:23,577 strategy [INFO] Twitter: #News Alleged Bitcoin creator denies he's the one http://t.co/gmilO85smQ #DailyNews
2014-03-15 02:42:29,378 strategy [INFO] Twitter: RT @Tom_Cruis3: #News Alleged Bitcoin creator denies he's the one http://t.co/gmilO85smQ #DailyNews
2014-03-15 02:42:38,012 strategy [INFO] Twitter: Need for speed dulu at BTC XXI
2014-03-15 02:42:40,162 strategy [INFO] Price: 632.97\. Volume: 0.51896614.
2014-03-15 02:42:45,867 strategy [INFO] Twitter: Analysis of the leaked MTGOX database http://t.co/6ty8EupGh9 via @Reddit
2014-03-15 02:42:46,761 strategy [INFO] Twitter: [ANN] After MtGox implosion, this is the first exchange to implement transparent cold storage http://t.co/EyafH5jXsM #reddit #bitcoin
2014-03-15 02:42:46,825 strategy [INFO] Twitter: @abatalion @naval @cdixon you guys remember CentMail? http://t.co/iihgCS4OwJ would be interesting with a BTC twist.
2014-03-15 02:42:47,285 strategy [INFO] Twitter: Help me convince my Dad to mine Bitcoins! http://t.co/fxboBooINu #reddit #bitcoin
2014-03-15 02:42:47,492 strategy [INFO] Twitter: RT @VentureBeat: Warren Buffett: Bitcoin is a 'mirage' http://t.co/B1FcvZKJQS by @xBarryLevine
2014-03-15 02:42:47,625 strategy [INFO] Twitter: I believe in bitcoin as not only a easy exchange of value but an 'anti bank movement' with occupy wall street, environmentalists, cons...
2014-03-15 02:42:47,979 strategy [INFO] Twitter: Bitcoin protocol/algorithm is being managed by a bunch of people. Isn't that a vulnerability? http://t.co/HJaCkgC6zT #reddit #bitcoin
2014-03-15 02:42:48,388 strategy [INFO] Twitter: Does anyone still think Dorian Nakomoto is Satoshi Nakamoto? http://t.co/v2N8SEZzxC #reddit #bitcoin
2014-03-15 02:42:53,313 strategy [INFO] Twitter: Last sale price at #Bitstamp was $632.99 per #Bitcoin - Free SMS price alerts from 10 exchanges at http://t.co/jsM3JqlvZd
2014-03-15 02:42:54,058 strategy [INFO] Twitter: Last sale price at #BTCe was $623.00 per #Bitcoin - Free SMS price alerts from 10 exchanges at http://t.co/jsM3JqlvZd
2014-03-15 02:42:54,059 strategy [INFO] Twitter: Last sale price at #Coinbase was $632.99 per #Bitcoin - Free SMS price alerts from 10 exchanges at http://t.co/jsM3JqlvZd
2014-03-15 02:42:57,148 strategy [INFO] Twitter: GET PAID WITH USD OR BITCOIN TO PROMOTE LINKS!!!... http://t.co/HKANbuZQHM
2014-03-15 02:43:00,845 strategy [INFO] Twitter: We're back! Bitcoin expert Pete Watson explaining just how the incredible #cryptocurrency works #bitcoin #HongKong http://t.co/CJpTA6RujJ
2014-03-15 02:43:28,001 strategy [INFO] Twitter: Bitcoin's COO Explains What #Bitcoin Is http://t.co/cQ1rVxYSUJ via @YouTube
2014-03-15 02:43:31,888 strategy [INFO] Twitter: #BINARY-OPTIONS! and BITCOIN! Trade Area! With fantastic profits of up to 1,000% per trade and even more. @ http://t.co/R9c9J4Q5VA
2014-03-15 02:43:42,148 strategy [INFO] Twitter: GET PAID WITH USD OR BITCOIN TO PROMOTE LINKS!!!... http://t.co/bD6cacFKTs
TA-Lib 集成
pyalgotrade.talibext.indicator 模块提供了与 TA-Lib 的 Python 包装器集成的功能(mrjbq7.github.com/ta-lib/
),使得可以直接使用 pyalgotrade.dataseries.DataSeries
或 pyalgotrade.dataseries.bards.BarDataSeries
实例调用 TA-Lib 函数,而不是使用 numpy 数组。
如果您熟悉talib模块,那么使用pyalgotrade.talibext.indicator模块应该很简单。在独立使用talib时,您会像这样做:
import numpy
import talib
data = numpy.random.random(100)
upper, middle, lower = talib.BBANDS(data, matype=talib.MA_T3)
要在您的策略中使用pyalgotrade.talibext.indicator模块,您应该这样做:
def onBars(self, bars):
closeDs = self.getFeed().getDataSeries("orcl").getCloseDataSeries()
upper, middle, lower = pyalgotrade.talibext.indicator.BBANDS(closeDs, 100, matype=talib.MA_T3)
if upper != None:
print "%s" % upper[-1]
pyalgotrade.talibext.indicator 模块中的每个函数接收一个或多个数据序列(大多数只接收一个)以及要从数据序列中使用的值的数量。在上面的例子中,我们正在计算过去 100 个收盘价的布林带。
如果参数名称是ds,那么你应该传递一个常规的pyalgotrade.dataseries.DataSeries
实例,就像上面的例子中所示的那样。
如果参数名称是barDs,那么你应该传递一个pyalgotrade.dataseries.bards.BarDataSeries
实例,就像下一个例子中所示的那样:
def onBars(self, bars):
barDs = self.getFeed().getDataSeries("orcl")
sar = indicator.SAR(barDs, 100)
if sar != None:
print "%s" % sar[-1]
通过pyalgotrade.talibext.indicator模块可用以下 TA-Lib 函数:
pyalgotrade.talibext.indicator.``AD
(barDs, count)
查金 A/D 线
pyalgotrade.talibext.indicator.``ADOSC
(barDs, count, fastperiod=-2147483648, slowperiod=-2147483648)
查金 A/D 振荡器
pyalgotrade.talibext.indicator.``ADX
(barDs, count, timeperiod=-2147483648)
平均方向运动指数
pyalgotrade.talibext.indicator.``ADXR
(barDs, count, timeperiod=-2147483648)
平均方向运动指数评分
pyalgotrade.talibext.indicator.``APO
(ds, count, fastperiod=-2147483648, slowperiod=-2147483648, matype=0)
绝对价格振荡器
pyalgotrade.talibext.indicator.``AROON
(barDs, count, timeperiod=-2147483648)
阿隆
pyalgotrade.talibext.indicator.``AROONOSC
(barDs, count, timeperiod=-2147483648)
阿隆振荡器
pyalgotrade.talibext.indicator.``ATR
(barDs, count, timeperiod=-2147483648)
平均真实波幅
pyalgotrade.talibext.indicator.``AVGPRICE
(barDs, count)
平均价格
pyalgotrade.talibext.indicator.``BBANDS
(ds, count, timeperiod=-2147483648, nbdevup=-4e+37, nbdevdn=-4e+37, matype=0)
布林带
pyalgotrade.talibext.indicator.``BETA
(ds1, ds2, count, timeperiod=-2147483648)
贝塔
pyalgotrade.talibext.indicator.``BOP
(barDs, count)
力量平衡
pyalgotrade.talibext.indicator.``CCI
(barDs, count, timeperiod=-2147483648)
商品通道指数
pyalgotrade.talibext.indicator.``CDL2CROWS
(barDs, count)
两只乌鸦
pyalgotrade.talibext.indicator.``CDL3BLACKCROWS
(barDs, count)
三只黑乌鸦
pyalgotrade.talibext.indicator.``CDL3INSIDE
(barDs, count)
三内上涨/下跌
pyalgotrade.talibext.indicator.``CDL3LINESTRIKE
(barDs, count)
三线攻击
pyalgotrade.talibext.indicator.``CDL3OUTSIDE
(barDs, count)
三外上涨/下跌
pyalgotrade.talibext.indicator.``CDL3STARSINSOUTH
(barDs, count)
南方三星
pyalgotrade.talibext.indicator.``CDL3WHITESOLDIERS
(barDs, count)
三个白兵
pyalgotrade.talibext.indicator.``CDLABANDONEDBABY
(barDs, count, penetration=-4e+37)
遗弃的婴儿
pyalgotrade.talibext.indicator.``CDLADVANCEBLOCK
(barDs, count)
先进块
pyalgotrade.talibext.indicator.``CDLBELTHOLD
(barDs, count)
饽饽持仓
pyalgotrade.talibext.indicator.``CDLBREAKAWAY
(barDs, count)
脱钩
pyalgotrade.talibext.indicator.``CDLCLOSINGMARUBOZU
(barDs, count)
收盘光头光脚
pyalgotrade.talibext.indicator.``CDLCONCEALBABYSWALL
(barDs, count)
掩盖婴儿燕
pyalgotrade.talibext.indicator.``CDLCOUNTERATTACK
(barDs, count)
反击模式
pyalgotrade.talibext.indicator.``CDLDARKCLOUDCOVER
(barDs, count, penetration=-4e+37)
乌云压顶
pyalgotrade.talibext.indicator.``CDLDOJI
(barDs, count)
十字星
pyalgotrade.talibext.indicator.``CDLDOJISTAR
(barDs, count)
十字星
pyalgotrade.talibext.indicator.``CDLDRAGONFLYDOJI
(barDs, count)
蜻蜓十字
pyalgotrade.talibext.indicator.``CDLENGULFING
(barDs, count)
吞没模式
pyalgotrade.talibext.indicator.``CDLEVENINGDOJISTAR
(barDs, count, penetration=-4e+37)
傍晚十字星
pyalgotrade.talibext.indicator.``CDLEVENINGSTAR
(barDs, count, penetration=-4e+37)
傍晚之星
pyalgotrade.talibext.indicator.``CDLGAPSIDESIDEWHITE
(barDs, count)
上/下缺口并排的白色线条
pyalgotrade.talibext.indicator.``CDLGRAVESTONEDOJI
(barDs, count)
墓碑十字
pyalgotrade.talibext.indicator.``CDLHAMMER
(barDs, count)
锤子
pyalgotrade.talibext.indicator.``CDLHANGINGMAN
(barDs, count)
吊人
pyalgotrade.talibext.indicator.``CDLHARAMI
(barDs, count)
孕线模式
pyalgotrade.talibext.indicator.``CDLHARAMICROSS
(barDs, count)
孕线交叉模式
pyalgotrade.talibext.indicator.``CDLHIGHWAVE
(barDs, count)
高浪蜡烛
pyalgotrade.talibext.indicator.``CDLHIKKAKE
(barDs, count)
吸星大法
pyalgotrade.talibext.indicator.``CDLHIKKAKEMOD
(barDs, count)
修改的吸星大法
pyalgotrade.talibext.indicator.``CDLHOMINGPIGEON
(barDs, count)
家鸽
pyalgotrade.talibext.indicator.``CDLIDENTICAL3CROWS
(barDs, count)
相同的三乌鸦
pyalgotrade.talibext.indicator.``CDLINNECK
(barDs, count)
脖颈模式
pyalgotrade.talibext.indicator.``CDLINVERTEDHAMMER
(barDs, count)
倒锤子
pyalgotrade.talibext.indicator.``CDLKICKING
(barDs, count)
踢
pyalgotrade.talibext.indicator.``CDLKICKINGBYLENGTH
(barDs, count)
踢 - 牛/熊由更长的光头确定
pyalgotrade.talibext.indicator.``CDLLADDERBOTTOM
(barDs, count)
梯底
pyalgotrade.talibext.indicator.``CDLLONGLEGGEDDOJI
(barDs, count)
长腿十字星
pyalgotrade.talibext.indicator.``CDLLONGLINE
(barDs, count)
长线蜡烛
pyalgotrade.talibext.indicator.``CDLMARUBOZU
(barDs, count)
光头
pyalgotrade.talibext.indicator.``CDLMATCHINGLOW
(barDs, count)
匹配低位
pyalgotrade.talibext.indicator.``CDLMATHOLD
(barDs, count, penetration=-4e+37)
矩阵持有
pyalgotrade.talibext.indicator.``CDLMORNINGDOJISTAR
(barDs, count, penetration=-4e+37)
晨星十字
pyalgotrade.talibext.indicator.``CDLMORNINGSTAR
(barDs, count, penetration=-4e+37)
晨星
pyalgotrade.talibext.indicator.``CDLONNECK
(barDs, count)
在脖子模式
pyalgotrade.talibext.indicator.``CDLPIERCING
(barDs, count)
刺透模式
pyalgotrade.talibext.indicator.``CDLRICKSHAWMAN
(barDs, count)
面包车人
pyalgotrade.talibext.indicator.``CDLRISEFALL3METHODS
(barDs, count)
上升/下降三法
pyalgotrade.talibext.indicator.``CDLSEPARATINGLINES
(barDs, count)
分隔线
pyalgotrade.talibext.indicator.``CDLSHOOTINGSTAR
(barDs, count)
长尾锤
pyalgotrade.talibext.indicator.``CDLSHORTLINE
(barDs, count)
短线蜡烛
pyalgotrade.talibext.indicator.``CDLSPINNINGTOP
(barDs, count)
陀螺顶
pyalgotrade.talibext.indicator.``CDLSTALLEDPATTERN
(barDs, count)
停滞模式
pyalgotrade.talibext.indicator.``CDLSTICKSANDWICH
(barDs, count)
杆子三明治
pyalgotrade.talibext.indicator.``CDLTAKURI
(barDs, count)
打瞌睡(底部)
pyalgotrade.talibext.indicator.``CDLTASUKIGAP
(barDs, count)
领带缺口
pyalgotrade.talibext.indicator.``CDLTHRUSTING
(barDs, count)
冲刺模式
pyalgotrade.talibext.indicator.``CDLTRISTAR
(barDs, count)
三星模式
pyalgotrade.talibext.indicator.``CDLUNIQUE3RIVER
(barDs, count)
独特的三江
pyalgotrade.talibext.indicator.``CDLUPSIDEGAP2CROWS
(barDs, count)
上缺口两乌鸦
pyalgotrade.talibext.indicator.``CDLXSIDEGAP3METHODS
(barDs, count)
上缺口/下缺口三法
pyalgotrade.talibext.indicator.``CMO
(ds, count, timeperiod=-2147483648)
查德动量振荡器
pyalgotrade.talibext.indicator.``CORREL
(ds1, ds2, count, timeperiod=-2147483648)
皮尔逊相关系数(r)
pyalgotrade.talibext.indicator.``DEMA
(ds, count, timeperiod=-2147483648)
双指数移动平均
pyalgotrade.talibext.indicator.``DX
(barDs, count, timeperiod=-2147483648)
方向运动指数
pyalgotrade.talibext.indicator.``EMA
(ds, count, timeperiod=-2147483648)
指数移动平均
pyalgotrade.talibext.indicator.``HT_DCPERIOD
(ds, count)
Hilbert 变换 - 主导周期
pyalgotrade.talibext.indicator.``HT_DCPHASE
(ds, count)
Hilbert 变换 - 主导周期相位
pyalgotrade.talibext.indicator.``HT_PHASOR
(ds, count)
Hilbert 变换 - 相量分量
pyalgotrade.talibext.indicator.``HT_SINE
(ds, count)
Hilbert 变换 - 正弦波
pyalgotrade.talibext.indicator.``HT_TRENDLINE
(ds, count)
Hilbert 变换 - 瞬时趋势线
pyalgotrade.talibext.indicator.``HT_TRENDMODE
(ds, count)
Hilbert 变换 - 趋势 vs 周期模式
pyalgotrade.talibext.indicator.``KAMA
(ds, count, timeperiod=-2147483648)
Kaufman 自适应移动平均
pyalgotrade.talibext.indicator.``LINEARREG
(ds, count, timeperiod=-2147483648)
线性回归
pyalgotrade.talibext.indicator.``LINEARREG_ANGLE
(ds, count, timeperiod=-2147483648)
线性回归角度
pyalgotrade.talibext.indicator.``LINEARREG_INTERCEPT
(ds, count, timeperiod=-2147483648)
线性回归截距
pyalgotrade.talibext.indicator.``LINEARREG_SLOPE
(ds, count, timeperiod=-2147483648)
线性回归斜率
pyalgotrade.talibext.indicator.``MA
(ds, count, timeperiod=-2147483648, matype=0)
所有移动平均
pyalgotrade.talibext.indicator.``MACD
(ds, count, fastperiod=-2147483648, slowperiod=-2147483648, signalperiod=-2147483648)
移动平均收敛/发散
pyalgotrade.talibext.indicator.``MACDEXT
(ds, count, fastperiod=-2147483648, fastmatype=0, slowperiod=-2147483648, slowmatype=0, signalperiod=-2147483648, signalmatype=0)
具有可控制 MA 类型的 MACD
pyalgotrade.talibext.indicator.``MACDFIX
(ds, count, signalperiod=-2147483648)
移动平均收敛/发散 修正 12/26
pyalgotrade.talibext.indicator.``MAMA
(ds, count, fastlimit=-4e+37, slowlimit=-4e+37)
MESA 自适应移动平均
pyalgotrade.talibext.indicator.``MAX
(ds, count, timeperiod=-2147483648)
一段时间内的最高值
pyalgotrade.talibext.indicator.``MAXINDEX
(ds, count, timeperiod=-2147483648)
指定周期内最高值的索引
pyalgotrade.talibext.indicator.``MEDPRICE
(barDs, count)
中位价
pyalgotrade.talibext.indicator.``MFI
(barDs, count, timeperiod=-2147483648)
资金流量指标
pyalgotrade.talibext.indicator.``MIDPOINT
(ds, count, timeperiod=-2147483648)
一段时间内的中点
pyalgotrade.talibext.indicator.``MIDPRICE
(barDs, count, timeperiod=-2147483648)
一段时间内的中点价格
pyalgotrade.talibext.indicator.``MIN
(ds, count, timeperiod=-2147483648)
指定周期内的最低值
pyalgotrade.talibext.indicator.``MININDEX
(ds, count, timeperiod=-2147483648)
在指定时间段内的最低值的指数
pyalgotrade.talibext.indicator.``MINMAX
(ds, count, timeperiod=-2147483648)
在指定时间段内的最低值和最高值
pyalgotrade.talibext.indicator.``MINMAXINDEX
(ds, count, timeperiod=-2147483648)
在指定时间段内的最低值和最高值的指数
pyalgotrade.talibext.indicator.``MINUS_DI
(barDs, count, timeperiod=-2147483648)
负向动向指标
pyalgotrade.talibext.indicator.``MINUS_DM
(barDs, count, timeperiod=-2147483648)
负向动向指数
pyalgotrade.talibext.indicator.``MOM
(ds, count, timeperiod=-2147483648)
动量
pyalgotrade.talibext.indicator.``NATR
(barDs, count, timeperiod=-2147483648)
归一化平均真实波幅
pyalgotrade.talibext.indicator.``OBV
(ds1, volumeDs, count)
量价均衡指标
pyalgotrade.talibext.indicator.``PLUS_DI
(barDs, count, timeperiod=-2147483648)
正向动向指数
pyalgotrade.talibext.indicator.``PLUS_DM
(barDs, count, timeperiod=-2147483648)
正向动向指数
pyalgotrade.talibext.indicator.``PPO
(ds, count, fastperiod=-2147483648, slowperiod=-2147483648, matype=0)
百分比价格振荡器
pyalgotrade.talibext.indicator.``ROC
(ds, count, timeperiod=-2147483648)
变化率: ((price/prevPrice)-1)*100
pyalgotrade.talibext.indicator.``ROCP
(ds, count, timeperiod=-2147483648)
百分比价格波动率: (price-prevPrice)/prevPrice
pyalgotrade.talibext.indicator.``ROCR
(ds, count, timeperiod=-2147483648)
变化率比率: (price/prevPrice)
pyalgotrade.talibext.indicator.``ROCR100
(ds, count, timeperiod=-2147483648)
变化率比率 100 比例: (price/prevPrice)*100
pyalgotrade.talibext.indicator.``RSI
(ds, count, timeperiod=-2147483648)
相对强弱指标
pyalgotrade.talibext.indicator.``SAR
(barDs, count, acceleration=-4e+37, maximum=-4e+37)
抛物线转向
pyalgotrade.talibext.indicator.``SAREXT
(barDs, count, startvalue=-4e+37, offsetonreverse=-4e+37, accelerationinitlong=-4e+37, accelerationlong=-4e+37, accelerationmaxlong=-4e+37, accelerationinitshort=-4e+37, accelerationshort=-4e+37, accelerationmaxshort=-4e+37)
抛物线转向-扩展
pyalgotrade.talibext.indicator.``SMA
(ds, count, timeperiod=-2147483648)
简单移动平均线
pyalgotrade.talibext.indicator.``STDDEV
(ds, count, timeperiod=-2147483648, nbdev=-4e+37)
标准差
pyalgotrade.talibext.indicator.``STOCH
(barDs, count, fastk_period=-2147483648, slowk_period=-2147483648, slowk_matype=0, slowd_period=-2147483648, slowd_matype=0)
随机指标
pyalgotrade.talibext.indicator.``STOCHF
(barDs, count, fastk_period=-2147483648, fastd_period=-2147483648, fastd_matype=0)
快速随机指标
pyalgotrade.talibext.indicator.``STOCHRSI
(ds, count, timeperiod=-2147483648, fastk_period=-2147483648, fastd_period=-2147483648, fastd_matype=0)
随机相对强度指数
pyalgotrade.talibext.indicator.``SUM
(ds, count, timeperiod=-2147483648)
求和
pyalgotrade.talibext.indicator.``T3
(ds, count, timeperiod=-2147483648, vfactor=-4e+37)
三重指数移动平均线(T3)
pyalgotrade.talibext.indicator.``TEMA
(ds, count, timeperiod=-2147483648)
三重指数移动平均线
pyalgotrade.talibext.indicator.``TRANGE
(barDs, count)
真实范围
pyalgotrade.talibext.indicator.``TRIMA
(ds, count, timeperiod=-2147483648)
三角形移动平均
pyalgotrade.talibext.indicator.``TRIX
(ds, count, timeperiod=-2147483648)
三重平滑 EMA 的 1 日变化率(ROC)
pyalgotrade.talibext.indicator.``TSF
(ds, count, timeperiod=-2147483648)
时间序列预测
pyalgotrade.talibext.indicator.``TYPPRICE
(barDs, count)
典型价格
pyalgotrade.talibext.indicator.``ULTOSC
(barDs, count, timeperiod1=-2147483648, timeperiod2=-2147483648, timeperiod3=-2147483648)
终极振荡器
pyalgotrade.talibext.indicator.``VAR
(ds, count, timeperiod=-2147483648, nbdev=-4e+37)
方差
pyalgotrade.talibext.indicator.``WCLPRICE
(barDs, count)
加权收盘价
pyalgotrade.talibext.indicator.``WILLR
(barDs, count, timeperiod=-2147483648)
威廉%R
pyalgotrade.talibext.indicator.``WMA
(ds, count, timeperiod=-2147483648)
加权移动平均线
计算投资 Part I
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/compinvpart1.html
2012 年我参加了 计算投资 Part I 课程,我必须完成一系列的作业,其中之一我使用了 PyAlgoTrade。
作业 1
对于这个作业,我必须选择 4 只股票,在 2011 年投资总额为 $1000000,并计算:
- 最终投资组合价值
- 年度回报
- 平均每日回报
- 每日回报的标准差
- 夏普比率
使用以下命令下载数据:
python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="IBM" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily
python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="AES" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily
python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="AIG" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily
python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="ORCL" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily
尽管交付成果是一个 Excel 电子表格,但我使用了这段代码验证了结果:
from __future__ import print_function
from pyalgotrade import strategy
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.stratanalyzer import returns
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.utils import stats
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed):
super(MyStrategy, self).__init__(feed, 1000000)
# We wan't to use adjusted close prices instead of close.
self.setUseAdjustedValues(True)
# Place the orders to get them processed on the first bar.
orders = {
"ibm": 1996,
"aes": 22565,
"aig": 5445,
"orcl": 8582,
}
for instrument, quantity in orders.items():
self.marketOrder(instrument, quantity, onClose=True, allOrNone=True)
def onBars(self, bars):
pass
# Load the bar feed from the CSV file
feed = quandlfeed.Feed()
feed.addBarsFromCSV("ibm", "WIKI-IBM-2011-quandl.csv")
feed.addBarsFromCSV("aes", "WIKI-AES-2011-quandl.csv")
feed.addBarsFromCSV("aig", "WIKI-AIG-2011-quandl.csv")
feed.addBarsFromCSV("orcl", "WIKI-ORCL-2011-quandl.csv")
# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)
# Attach returns and sharpe ratio analyzers.
retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
# Run the strategy
myStrategy.run()
# Print the results.
print("Final portfolio value: $%.2f" % myStrategy.getResult())
print("Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100))
print("Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100))
print("Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns())))
print("Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
结果如下:
Final portfolio value: $876350.83
Anual return: -12.36 %
Average daily return: -0.04 %
Std. dev. daily return: 0.0176
Sharpe ratio: -0.33
目录
-
计算投资 Part I
- 作业 1
示例策略
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/samples.html
动量
-
VWAP 动量交易
-
SMA 交叉
-
利用移动平均线交叉进行市场定时
均值回归
-
欧尼·陈的黄金与黄金矿工
-
布林带
-
RSI2
其他
- Quandl 整合
目录
-
示例策略
-
动量
-
均值回归
-
其他
-
VWAP 动量交易
原文:
gbeced.github.io/pyalgotrade/docs/v0.20/html/sample_vwap_momentum.html
此示例基于动量交易
from __future__ import print_function
from pyalgotrade import strategy
from pyalgotrade import plotter
from pyalgotrade.tools import quandl
from pyalgotrade.technical import vwap
from pyalgotrade.stratanalyzer import sharpe
class VWAPMomentum(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, vwapWindowSize, threshold):
super(VWAPMomentum, self).__init__(feed)
self.__instrument = instrument
self.__vwap = vwap.VWAP(feed[instrument], vwapWindowSize)
self.__threshold = threshold
def getVWAP(self):
return self.__vwap
def onBars(self, bars):
vwap = self.__vwap[-1]
if vwap is None:
return
shares = self.getBroker().getShares(self.__instrument)
price = bars[self.__instrument].getClose()
notional = shares * price
if price > vwap * (1 + self.__threshold) and notional < 1000000:
self.marketOrder(self.__instrument, 100)
elif price < vwap * (1 - self.__threshold) and notional > 0:
self.marketOrder(self.__instrument, -100)
def main(plot):
instrument = "AAPL"
vwapWindowSize = 5
threshold = 0.01
# Download the bars.
feed = quandl.build_feed("WIKI", [instrument], 2011, 2012, ".")
strat = VWAPMomentum(feed, instrument, vwapWindowSize, threshold)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
strat.attachAnalyzer(sharpeRatioAnalyzer)
if plot:
plt = plotter.StrategyPlotter(strat, True, False, True)
plt.getInstrumentSubplot(instrument).addDataSeries("vwap", strat.getVWAP())
strat.run()
print("Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05))
if plot:
plt.plot()
if __name__ == "__main__":
main(True)
这是输出应该呈现的样子:
2017-07-24 22:43:34,182 quandl [INFO] Downloading AAPL 2011 to ./WIKI-AAPL-2011-quandl.csv
2017-07-24 22:43:36,415 quandl [INFO] Downloading AAPL 2012 to ./WIKI-AAPL-2012-quandl.csv
Sharpe ratio: 0.89
这是图表应该呈现的样子:
通过调整 VWAP 和阈值参数,您可以获得更好的回报。
标签:count,indicator,20,talibext,self,pyalgotrade,文档,strategy,PyAlgoTrade From: https://www.cnblogs.com/apachecn/p/18189080