终极振荡器
原文:
www.backtrader.com/blog/posts/2016-06-22-ultimate-oscillator/ultimate-oscillator/
当启动backtrader的开发时,其中一个目标是使其非常容易(至少对于作者本人来说)开发新的Indicators以测试数学和视觉上的想法。
Ticket #102是关于将UltimateOscillator添加到backtrader的武器库中
注意
它将在下一个版本中添加,同时可以使用下面的代码来使用它。
如票号中所示的参考资料:
以及在:
这里不需要重复。
引用自参考资料:
BP = Close - Minimum(Low or Prior Close) TR = Maximum(High or Prior Close) - Minimum(Low or Prior Close) Average7 = (7-period BP Sum) / (7-period TR Sum) Average14 = (14-period BP Sum) / (14-period TR Sum) Average28 = (28-period BP Sum) / (28-period TR Sum) UO = 100 x [(4 x Average7)+(2 x Average14)+Average28]/(4+2+1)
摘要:
- 首先从
bt.Indicator中派生子类,以确保整个机制运作正常:
class UltimateOscillator(bt.Indicator):`
- 它有 1 个输出行:我们将命名为
uo:
lines = ('uo',)`
- 它有 3 个参数,定义了 3 个周期,默认值为
7、14和28。将命名为p1、p2和p3:
params = (('p1', 7), ('p2', 14), ('p3', 28), )`
- 计算使用了backtrader中已经内置的一些东西
最小(低价或前收盘价):这是由Welles Wilder为RSI指标定义的TrueLow。因此,可以计算出BP或买入压力:
bp = self.data.close - TrueLow(self.data)`
最大(低价或前收盘价) - 最小(低价或前收盘价):这是由Welles Wilder为RSI指标定义的TrueRange(可以表示为TrueHigh - TrueLow)。因此,下一个计算就像这样简单:
tr = TrueRange(self.data)`
- 其余部分都是纯数学运算,使用
SumN来加上最新的p1、p2、p3周期的bp和tr,加上加权计算:
av7 = SumN(bp, period=self.p.p1) / SumN(tr, period=self.p.p1) av14 = SumN(bp, period=self.p.p2) / SumN(tr, period=self.p.p2) av28 = SumN(bp, period=self.p.p3) / SumN(tr, period=self.p.p3) uo = 100.0 * (4.0 * av7 + 2.0 * av14 + av28) / (4.0 + 2.0 + 1.0)`
- 最后将计算分配给定义的
uo线:
self.lines.uo = uo`
看起来比实际长度长(包括导入的全部代码)位于底部。
由于我们不仅想要值,还想要一个漂亮的图表,就像Stockcharts提供的图表一样,我们将添加两个额外的触摸:
- 2 个参数确定放置水平线的位置,以限定超买和超卖区域(类似于
RSI或Stochastic):
('upperband', 70.0), ('lowerband', 30.0),`
- 以及绘图初始化代码以使用参数。像Stockcharts中的绘图一样,在
10、50和90处添加刻度:
def _plotinit(self): baseticks = [10.0, 50.0, 90.0] hlines = [self.p.upperband, self.p.lowerband] self.plotinfo.plotyhlines = hlines self.plotinfo.plotyticks = baseticks + hlines`
为了测试和进一步使用backtrader提供的现有工具,将使用与backtrader一起安装的btrun可执行文件。
- 指标存储在名为
ultimateoscillator.py的文件中 - 使用的数据是backtrader源代码中可用的数据样本之一
- 该指标将使用默认参数添加两次,并使用较短期的参数添加两次
执行:
btrun \ --nostdstats \ --data 2005-2006-day-001.txt \ --indicator ultimateoscillator:UltimateOscillator \ --indicator ultimateoscillator:UltimateOscillator:p1=4,p2=8,p3=16 \ --plot
注意
使用–nostdstats来移除图表中的一些观察者。在这种情况下,无需跟踪现金和价值
输出只是显示 UltimateOscillator 演变的图表。
UltimateOscillator 代码:
from __future__ import (absolute_import, division, print_function, unicode_literals) import backtrader as bt from backtrader.indicators import SumN, TrueLow, TrueRange class UltimateOscillator(bt.Indicator): ''' Formula: # Buying Pressure = Close - TrueLow BP = Close - Minimum(Low or Prior Close) # TrueRange = TrueHigh - TrueLow TR = Maximum(High or Prior Close) - Minimum(Low or Prior Close) Average7 = (7-period BP Sum) / (7-period TR Sum) Average14 = (14-period BP Sum) / (14-period TR Sum) Average28 = (28-period BP Sum) / (28-period TR Sum) UO = 100 x [(4 x Average7)+(2 x Average14)+Average28]/(4+2+1) See: - https://en.wikipedia.org/wiki/Ultimate_oscillator - http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ultimate_oscillator ''' lines = ('uo',) params = (('p1', 7), ('p2', 14), ('p3', 28), ('upperband', 70.0), ('lowerband', 30.0), ) def _plotinit(self): baseticks = [10.0, 50.0, 90.0] hlines = [self.p.upperband, self.p.lowerband] self.plotinfo.plotyhlines = hlines self.plotinfo.plotyticks = baseticks + hlines def __init__(self): bp = self.data.close - TrueLow(self.data) tr = TrueRange(self.data) av7 = SumN(bp, period=self.p.p1) / SumN(tr, period=self.p.p1) av14 = SumN(bp, period=self.p.p2) / SumN(tr, period=self.p.p2) av28 = SumN(bp, period=self.p.p3) / SumN(tr, period=self.p.p3) uo = 100.0 * (4.0 * av7 + 2.0 * av14 + av28) / (4.0 + 2.0 + 1.0) self.lines.uo = uo
实时数据/实时交易
原文:
www.backtrader.com/blog/posts/2016-06-21-livedata-feed/live-data-feed/
从版本1.5.0开始,backtrader 支持实时数据源和实时交易。第一个集成实体是:
- 交互经纪人
这是平台创意最初设定的长期目标。设计理念已被证明足够灵活,以适应所需的变化。同时保持相同的界面,这意味着:一次回测,多次交易。相同的代码/api/基本元素/通知用于回测和实时数据提供/交易。
将平台命名为back + trader是有意义的,尽管它本来可以保持纯粹的回测。但不再是。
有什么新变化:
- 存储概念是为像交互经纪人这样一次性提供数据和经纪设施的实体提供一个集成的概念
- 从存储和/或数据源向策略和/或大脑发送新通知
- 时间管理支持…因为一个人可能会从任何地方交易纽约的产品,时间必须保持一致
- 努力在重采样/重播上尽快交付条形图,或者如果市场没有交易,则不要太晚(没有人希望在 30 秒后收到 5 秒重采样的条形图,因为没有中间的 ticks)
- 当然有许多小的内部变化
已经进行了大量的集成测试,并且一个名为ibtest的大样本已经集成在源代码中,但由于这是第 1 个版本,仍可能存在一些边缘情况。如果您决定尝试一下,请执行第 1 个针对交互经纪人提供的模拟交易账户(通常在端口7497而不是7496上运行)。
注意
请确保对与数据断开连接相关的固有风险感到舒适,软件中存在的错误(TWS和backtrader),您自己软件中的错误并监控您的活动。
backtrader不会对交易者可能遭受的任何损失负责(它也不会分担任何盈利)
交互经纪人支持什么:
- 指数(显然不用于交易),股票,期货,期权,期货期权和外汇
- 在连接开始和重新连接后进行回填
- 通知从实时到回填和反之的变化
- backtrader中已经存在的订单类型:
市价,限价,止损限价和收盘(又称收盘市价)
平台的意图不是重新发明轮子,因此需要/可选使用交互经纪人设施:
- 必需:
IbPy与交互经纪人的 TWS进行接口
IB的文档指示如何安装它,如果尚未成为您的武器库的一部分 - 可选:
pytz以自动设置产品的时区。
最终用户可以直接将其他tzinfo兼容的实例(来自pytz或自制的)作为数据源的参数,而不是依赖于自动确定。请参阅文档中的时间管理和文档的IB特定部分。
!!! 注意
If no `pytz` is detected and no `tzinfo` compatible instance is supplied to the *data feed*, the time delivered by the platform will be `UTC
尽可能多地进行了文档记录,并且可以在通常的文档链接中找到:
从示例ibtest对TWS Demo进行了几次运行。
首先:对TWTR进行重新采样为 5 秒:
$ ./ibtest.py --port 7497 --data0 TWTR --resample --timeframe Seconds --compression 5
输出:
Server Version: 76 TWS Time at connection:20160620 22:37:37 CET -------------------------------------------------- Strategy Created -------------------------------------------------- Timezone from ContractDetails: EST5EDT Datetime, Open, High, Low, Close, Volume, OpenInterest, SMA ***** STORE NOTIF: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:ibdemo> ***** STORE NOTIF: <error id=-1, errorCode=2106, errorMsg=HMDS data farm connection is OK:demohmds> ***** DATA NOTIF: CONNECTED 0001, 2016-06-20T14:37:35.000000, 15.96, 15.97, 15.96, 15.96, 0.0, 0, nan ***** DATA NOTIF: DELAYED 0002, 2016-06-20T14:37:40.000000, 15.96, 15.97, 15.96, 15.96, 0.0, 0, nan 0003, 2016-06-20T14:37:45.000000, 15.96, 15.97, 15.96, 15.97, 0.0, 0, nan 0004, 2016-06-20T14:37:50.000000, 15.96, 15.98, 15.94, 15.94, 0.0, 0, nan 0005, 2016-06-20T14:37:55.000000, 15.97, 15.97, 15.96, 15.97, 0.0, 0, 15.96 ... 1441, 2016-06-20T16:37:35.000000, 16.03, 16.03, 16.02, 16.03, 0.0, 0, 16.026 1442, 2016-06-20T16:37:40.000000, 16.11, 16.11, 16.11, 16.11, 2.0, 0, 16.044 ***** DATA NOTIF: LIVE 1443, 2016-06-20T16:37:45.000000, 16.1, 16.11, 16.1, 16.11, 5.0, 0, 16.06 1444, 2016-06-20T16:37:50.000000, 16.11, 16.11, 16.1, 16.1, 14.0, 0, 16.076 ...
注意
执行环境安装了pytz。
以下情况可观察到:
- 第 1 行(来自
IbPy本身)显示连接到服务器已成功,数据源已经确定了资产的操作时区:EST5EDT(又称EST又称US/Eastern)。
注意TWS在开头报告的本地时间(在时区CET又称Europe/Berlin),但资产落后6小时。
资产报告在交易场所的时间。如果你认为你真的想要改变这个,并且有关这种行为的理由,请查阅文档。 - 一些来自Store的通知,在这种情况下,TWS表示与不同数据中心的连接正常。这是通过Strategy中重写的方法打印出来的。
- 数据通知,比如:
CONNECTED:告知策略连接到TWS可用。DELAYED:接收到的数据不是实时数据。正在进行回补(历史数据)。
因为重新采样参数为秒/5,所以单个请求中可以下载的 5 秒条的最大数量大约为 1440。LIVE:一旦平台赶上回补,并且队列减少到实时数据,通知会告知策略。
从条 1443 开始,数据是实时数据。
注意
因为正在进行重新采样,这些数据不是 tick 数据,并且会在 5 秒周期结束时传递。请查看IBData中qcheck参数文档,了解重新采样条会因为平台没有发送新的 tick 而延迟多快(因为没有新的 tick,平台无法确定当前重新采样的条是否已经结束)。
让我们做同样的事情,但强制断开连接(网络接口被禁用了 20 秒):
$ ./ibtest.py --port 7497 --data0 TWTR --resample --timeframe Seconds --compression 5
输出(跳过初始已知部分):
... 1440, 2016-06-20T18:16:20.000000, 16.05, 16.05, 16.04, 16.04, 0.0, 0, 16.048 1441, 2016-06-20T18:16:25.000000, 16.05, 16.05, 16.05, 16.05, 0.0, 0, 16.05 ***** DATA NOTIF: LIVE 1442, 2016-06-20T18:16:30.000000, 15.9, 15.9, 15.89, 15.9, 11.0, 0, 16.02 ***** STORE NOTIF: <error id=-1, errorCode=1100, errorMsg=Connectivity between IB and TWS has been lost.> ***** STORE NOTIF: <error id=-1, errorCode=2105, errorMsg=HMDS data farm connection is broken:demohmds> ***** STORE NOTIF: <error id=-1, errorCode=2103, errorMsg=Market data farm connection is broken:ibdemo> 1443, 2016-06-20T18:16:35.000000, 15.9, 15.9, 15.89, 15.9, 28.0, 0, 15.988 ***** STORE NOTIF: <error id=-1, errorCode=1102, errorMsg=Connectivity between IB and TWS has been restored - data maintained.> ***** STORE NOTIF: <error id=-1, errorCode=2106, errorMsg=HMDS data farm connection is OK:demohmds> ***** STORE NOTIF: <error id=-1, errorCode=2104, errorMsg=Market data farm connection is OK:ibdemo> ***** DATA NOTIF: DELAYED 1444, 2016-06-20T18:16:40.000000, 16.04, 16.04, 16.03, 16.04, 0.0, 0, 15.986 1445, 2016-06-20T18:16:45.000000, 16.03, 16.04, 16.03, 16.04, 0.0, 0, 15.986 1446, 2016-06-20T18:16:50.000000, 16.04, 16.04, 16.03, 16.03, 0.0, 0, 15.982 1447, 2016-06-20T18:16:55.000000, 16.04, 16.04, 16.03, 16.04, 0.0, 0, 16.01 1448, 2016-06-20T18:17:00.000000, 16.03, 16.04, 16.03, 16.04, 0.0, 0, 16.038 1449, 2016-06-20T18:17:05.000000, 16.03, 16.04, 16.02, 16.03, 0.0, 0, 16.036 1450, 2016-06-20T18:17:10.000000, 15.9, 15.91, 15.9, 15.91, 3.0, 0, 16.01 ***** DATA NOTIF: LIVE 1451, 2016-06-20T18:17:15.000000, 15.92, 15.92, 15.9, 15.92, 9.0, 0, 15.988 1452, 2016-06-20T18:17:20.000000, 15.91, 15.91, 15.89, 15.89, 18.0, 0, 15.958 1453, 2016-06-20T18:17:25.000000, 15.89, 15.92, 15.89, 15.89, 24.0, 0, 15.928 ...
叙述:
- 在条 1442 之后,WLAN 接口已被禁用。
- TWS 通知到达,指示情况。
- 条 1443 是从重新采样器中提取的,因为平台在
18:16:30.000000和18:16:35.000000之间有一些 tick。 - 连接在大约
18:17:15恢复,但此数据不是立即传递的。 - 发现情况,并尝试在
18:16:35和18:17:15之间进行回补。
这可以通过通知DELAYED看到。数据不再是LIVE。 - 条 1444 至 1450(包括两端)提供了缺失的时间。
- 收到通知
LIVE,且条 1451 包含实时数据包。
注意
由于TWS不强制执行,因此存在一些情况,backtrader无法克服。 如果 TCP/IP 数据包某种方式丢失且IB服务器反应迟缓,TWS将花费很长时间来做出反应并通知连接丢失。
TWS甚至会传送清晰接收延迟的数据包,带有当前时间戳(通过突然爆发的数据包识别)
最后一些交易,用单个Market订单购买20K股的TWTR,并将它们分为 2 个10K的订单。
执行:
./ibtest.py --port 7497 --data0 TWTR --resample --timeframe Seconds --compression 5 --broker --trade --stake 20000
输出相当冗长,显示了订单执行的所有部分。总结一下:
... ***** DATA NOTIF: LIVE 1442, 2016-06-20T18:28:05.000000, 15.92, 15.93, 15.92, 15.93, 1748.0, 0, 16.03 -------------------------------------------------- ORDER BEGIN 2016-06-20 23:28:11.343000 Ref: 1 OrdType: 0 OrdType: Buy Status: 1 Status: Submitted Size: 20000 Price: 14.34 Price Limit: None ExecType: 0 ExecType: Market CommInfo: <backtrader.brokers.ibbroker.IBCommInfo object at 0x00000000040B9278> End of Session: 736136.166655 Info: AutoOrderedDict() Broker: <backtrader.brokers.ibbroker.IBBroker object at 0x0000000003E23470> Alive: True Ref: 1 orderId: 1 Action: BUY Size (ib): 20000 Lmt Price: 0.0 Aux Price: 0.0 OrderType: MKT Tif (Time in Force): GTC GoodTillDate: -------------------------------------------------- ORDER END ... 1443, 2016-06-20T18:28:10.000000, 15.93, 15.93, 15.92, 15.92, 10.0, 0, 16.004 -------------------------------------------------- ORDER BEGIN 2016-06-20 23:28:15.924000 Ref: 1 OrdType: 0 OrdType: Buy Status: 3 Status: Partial Size: 20000 Price: 14.34 Price Limit: None ExecType: 0 ExecType: Market CommInfo: <backtrader.brokers.ibbroker.IBCommInfo object at 0x00000000040B9278> End of Session: 736136.166655 Info: AutoOrderedDict() Broker: <backtrader.brokers.ibbroker.IBBroker object at 0x0000000003E23470> Alive: True Ref: 1 orderId: 1 Action: BUY Size (ib): 20000 Lmt Price: 0.0 Aux Price: 0.0 OrderType: MKT Tif (Time in Force): GTC GoodTillDate: -------------------------------------------------- ORDER END ... -------------------------------------------------- ORDER BEGIN 2016-06-20 23:28:20.972000 Ref: 1 OrdType: 0 OrdType: Buy Status: 4 Status: Completed Size: 20000 Price: 14.34 Price Limit: None ExecType: 0 ExecType: Market CommInfo: <backtrader.brokers.ibbroker.IBCommInfo object at 0x00000000040B9278> End of Session: 736136.166655 Info: AutoOrderedDict() Broker: <backtrader.brokers.ibbroker.IBBroker object at 0x0000000003E23470> Alive: False Ref: 1 orderId: 1 Action: BUY Size (ib): 20000 Lmt Price: 0.0 Aux Price: 0.0 OrderType: MKT Tif (Time in Force): GTC GoodTillDate: -------------------------------------------------- ORDER END 1445, 2016-06-20T18:28:20.000000, 15.92, 15.93, 15.92, 15.93, 21.0, 0, 15.954 ...
发生了以下情况:
- 数据正常接收
- 发出了一个执行类型为
Market的BUY20K
- 收到
Submitted和Accepted通知(仅显示了Submitted) - 一连串的
Partial执行(仅显示了 1 个),直到收到Completed。
- 实际执行未显示,但可在收到的
order实例下的order.executed中找到 - 虽然未显示,但发出了 2 个
MarketSELL订单以撤消操作
屏幕截图显示了在一个晚上进行两次不同运行后TWS中的日志
示例可以做更多,并且旨在对设施进行彻底测试,如果可能的话发现任何问题。
用法:
$ ./ibtest.py --help usage: ibtest.py [-h] [--exactbars EXACTBARS] [--plot] [--stopafter STOPAFTER] [--usestore] [--notifyall] [--debug] [--host HOST] [--qcheck QCHECK] [--port PORT] [--clientId CLIENTID] [--no-timeoffset] [--reconnect RECONNECT] [--timeout TIMEOUT] --data0 DATA0 [--data1 DATA1] [--timezone TIMEZONE] [--what WHAT] [--no-backfill_start] [--latethrough] [--no-backfill] [--rtbar] [--historical] [--fromdate FROMDATE] [--smaperiod SMAPERIOD] [--replay | --resample] [--timeframe {Ticks,MicroSeconds,Seconds,Minutes,Days,Weeks,Months,Years}] [--compression COMPRESSION] [--no-takelate] [--no-bar2edge] [--no-adjbartime] [--no-rightedge] [--broker] [--trade] [--donotsell] [--exectype {Market,Close,Limit,Stop,StopLimit}] [--stake STAKE] [--valid VALID] [--cancel CANCEL] Test Interactive Brokers integration optional arguments: -h, --help show this help message and exit --exactbars EXACTBARS exactbars level, use 0/-1/-2 to enable plotting (default: 1) --plot Plot if possible (default: False) --stopafter STOPAFTER Stop after x lines of LIVE data (default: 0) --usestore Use the store pattern (default: False) --notifyall Notify all messages to strategy as store notifs (default: False) --debug Display all info received form IB (default: False) --host HOST Host for the Interactive Brokers TWS Connection (default: 127.0.0.1) --qcheck QCHECK Timeout for periodic notification/resampling/replaying check (default: 0.5) --port PORT Port for the Interactive Brokers TWS Connection (default: 7496) --clientId CLIENTID Client Id to connect to TWS (default: random) (default: None) --no-timeoffset Do not Use TWS/System time offset for non timestamped prices and to align resampling (default: False) --reconnect RECONNECT Number of recconnection attempts to TWS (default: 3) --timeout TIMEOUT Timeout between reconnection attempts to TWS (default: 3.0) --data0 DATA0 data 0 into the system (default: None) --data1 DATA1 data 1 into the system (default: None) --timezone TIMEZONE timezone to get time output into (pytz names) (default: None) --what WHAT specific price type for historical requests (default: None) --no-backfill_start Disable backfilling at the start (default: False) --latethrough if resampling replaying, adjusting time and disabling time offset, let late samples through (default: False) --no-backfill Disable backfilling after a disconnection (default: False) --rtbar Use 5 seconds real time bar updates if possible (default: False) --historical do only historical download (default: False) --fromdate FROMDATE Starting date for historical download with format: YYYY-MM-DD[THH:MM:SS] (default: None) --smaperiod SMAPERIOD Period to apply to the Simple Moving Average (default: 5) --replay replay to chosen timeframe (default: False) --resample resample to chosen timeframe (default: False) --timeframe {Ticks,MicroSeconds,Seconds,Minutes,Days,Weeks,Months,Years} TimeFrame for Resample/Replay (default: Ticks) --compression COMPRESSION Compression for Resample/Replay (default: 1) --no-takelate resample/replay, do not accept late samples in new bar if the data source let them through (latethrough) (default: False) --no-bar2edge no bar2edge for resample/replay (default: False) --no-adjbartime no adjbartime for resample/replay (default: False) --no-rightedge no rightedge for resample/replay (default: False) --broker Use IB as broker (default: False) --trade Do Sample Buy/Sell operations (default: False) --donotsell Do not sell after a buy (default: False) --exectype {Market,Close,Limit,Stop,StopLimit} Execution to Use when opening position (default: Market) --stake STAKE Stake to use in buy operations (default: 10) --valid VALID Seconds to keep the order alive (0 means DAY) (default: None) --cancel CANCEL Cancel a buy order after n bars in operation, to be combined with orders like Limit (default: 0)
BackTrader 中文文档(二十四)(2)https://developer.aliyun.com/article/1505446