砖形图
原文:
www.backtrader.com/blog/posts/2017-06-26-renko-bricks/renko-bricks/
砖形图是一种以价格比时间更重要的方式展示价格演变的方法。这已经在backtrader的1.9.54.122版本中作为过滤器引入了。
Stockcharts对砖形图有一个很好的参考。请参阅StockCharts 上的砖形图
一些示例
注意
size=35和align=10.0参数适用于backtrader存储库中的示例数据。这些值必须针对每个数据资产进行微调。
首先,让我们将砖形图单独放在一个图表上:
$ ./renko.py --renko size=35,align=10.0 --plot
输出
人们可以看到图表立即显示出一些支撑/阻力区域,这是砖形图的主要优势之一。显然,X 轴上的时间演变不再是恒定的,而是被拉伸或压缩,取决于价格行动在期间是更静态还是移动了几个砖块。
为了更好地看到和欣赏效果,让我们将普通的价格条和砖形图放在一起在一个图表上:
$ ./renko.py --renko size=35,align=10.0 --plot --dual
输出
时间周期的拉伸和压缩现在更加明显。另一个要考虑的因素是价格行动的关注如何影响应用的指标,正如图表上显示的两个RSI指标所示。
示例用法
$ ./renko.py --help usage: renko.py [-h] [--data0 DATA0] [--fromdate FROMDATE] [--todate TODATE] [--cerebro kwargs] [--broker kwargs] [--sizer kwargs] [--strat kwargs] [--plot [kwargs]] [--renko kwargs] [--dual] Renko bricks sample optional arguments: -h, --help show this help message and exit --data0 DATA0 Data to read in (default: ../../datas/2005-2006-day-001.txt) --fromdate FROMDATE Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: ) --todate TODATE Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: ) --cerebro kwargs kwargs in key=value format (default: ) --broker kwargs kwargs in key=value format (default: ) --sizer kwargs kwargs in key=value format (default: ) --strat kwargs kwargs in key=value format (default: ) --plot [kwargs] kwargs in key=value format (default: ) --renko kwargs kwargs in key=value format (default: ) --dual put the filter on a second version of the data (default: False)
示例代码
from __future__ import (absolute_import, division, print_function, unicode_literals) import argparse import datetime import backtrader as bt class St(bt.Strategy): params = dict( ) def __init__(self): for d in self.datas: bt.ind.RSI(d) def next(self): pass def runstrat(args=None): args = parse_args(args) cerebro = bt.Cerebro() # Data feed kwargs kwargs = dict() # Parse from/to-date dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S' for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']): if a: strpfmt = dtfmt + tmfmt * ('T' in a) kwargs[d] = datetime.datetime.strptime(a, strpfmt) data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs) fkwargs = dict() fkwargs.update(**eval('dict(' + args.renko + ')')) if not args.dual: data0.addfilter(bt.filters.Renko, **fkwargs) cerebro.adddata(data0) else: cerebro.adddata(data0) data1 = data0.clone() data1.addfilter(bt.filters.Renko, **fkwargs) cerebro.adddata(data1) # Broker cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')')) # Sizer cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')')) # Strategy cerebro.addstrategy(St, **eval('dict(' + args.strat + ')')) # Execute kwargs = dict(stdstats=False) kwargs.update(**eval('dict(' + args.cerebro + ')')) cerebro.run(**kwargs) if args.plot: # Plot if requested to kwargs = dict(style='candle') kwargs.update(**eval('dict(' + args.plot + ')')) cerebro.plot(**kwargs) def parse_args(pargs=None): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=( 'Renko bricks sample' ) ) parser.add_argument('--data0', default='../../datas/2005-2006-day-001.txt', required=False, help='Data to read in') # Defaults for dates parser.add_argument('--fromdate', required=False, default='', help='Date[time] in YYYY-MM-DD[THH:MM:SS] format') parser.add_argument('--todate', required=False, default='', help='Date[time] in YYYY-MM-DD[THH:MM:SS] format') parser.add_argument('--cerebro', required=False, default='', metavar='kwargs', help='kwargs in key=value format') parser.add_argument('--broker', required=False, default='', metavar='kwargs', help='kwargs in key=value format') parser.add_argument('--sizer', required=False, default='', metavar='kwargs', help='kwargs in key=value format') parser.add_argument('--strat', required=False, default='', metavar='kwargs', help='kwargs in key=value format') parser.add_argument('--plot', required=False, default='', nargs='?', const='{}', metavar='kwargs', help='kwargs in key=value format') parser.add_argument('--renko', required=False, default='', metavar='kwargs', help='kwargs in key=value format') parser.add_argument('--dual', required=False, action='store_true', help='put the filter on a second version of the data') return parser.parse_args(pargs) if __name__ == '__main__': runstrat()
Backtrader:该基金
原文:
www.backtrader.com/blog/posts/2017-06-19-fund-tracking/fund-tracking/
backtrader已经有一段时间被使用,可以说是专业使用,除了一些银行和交易公司之外,还有Backtrader 基金。
历史
一群志同道合且相互认识已久的人决定走上开设(避险)基金的道路,并以backtrader作为交易理念的基石。有一件事情是不可或缺的:它必须是 100%受监管的(但不在开曼群岛或类似地方)
位置、传统和网络在欧盟首先,然后在西班牙放置重点,西班牙(以及其他一些地方)的立法允许伞形基金托管子基金,这使得可以用较少的资金和参与者数量创建一个完全受监管的基金。
还有……基金已被西班牙的监管机构CNMV(西班牙国家证券市场委员会)批准,ISIN为ES0131444038。链接:
对于能阅读西班牙语的人,backtrader的使用已在官方基金说明书中记录。
对于那些可能在某个时候决定走这条路的人,最重要的事情是:
- 官僚主义很慢,沿途会有很多问题
- 保持一切的记录(执行的操作、现金/净资产价值水平、头寸、杠杆)
- 向监管机构报告是必须的(因此需要收集和保持前述信息的良好组织)
- 遵循定义的风险/波动性水平不仅仅是一个指导方针
- 管理其他人的资金(OPM)是一种真正的心理负担。会有损失,会有问题。无论问题有多么善意和天真:它们都会产生影响。
backtrader是交易理念的基础,并且它已经找到了一个新的应用领域:报告。自定义的分析器和指标可以帮助控制风险/波动性,从而减轻了行政负担。
可能是因为我们年纪大了(而且是老派的),我们仍然更喜欢手动执行(自动执行将在未来某个时候接管)
下面描述的功能是为了辅助管理基金和回测资金进出以及绩效不再是追踪净资产价值的问题。
基金跟踪
在版本1.9.52.121中,backtrader中的经纪人不仅在现金/价值方面跟踪会计,而且像在基金中一样进行,即:
- 基金价值(实际基金份额的价值)
- 股份数量
通过这样做,我们可以模拟现金存款和提款,同时仍然跟踪实际表现,而常规会计会被现金流入/流出所扭曲。
除了经纪人的变化外,分析器和观察者也已经适应(那些与净资产价值有关的)以支持fund参数,以决定实际应该追踪什么。例如TimeReturn:
... cerebro.addanalyzer(bt.analyzers.TimeReturn) # auto-detect broker mode cerebro.addanalyzer(bt.analyzers.TimeReturn, fund=True) # track fund value cerebro.addanalyzer(bt.analyzers.TimeReturn, fund=False) # track net asset value ...
这是什么基金追踪?
想象一下使用案例(稍后在示例中):某人从 1000 货币单位开始,在每个月的 15 日添加 100 货币单位。12 个月后,账户中的总额为 2200。根据最初的持仓计算的回报率为
以通常的方式计算回报,这意味着在没有执行任何操作的情况下,年度回报率为120%。当然,这是不正确的。
为了缓解这个问题,不管账户的初始值如何,基金份额(fundvalue)的价值被设定为100.0。并且根据此值和起始净资产价值(1000货币单位),计算基金份额数量如下:
fundshares = 净资产价值 / 基金价值
在这种情况下,实际上是1000 / 100.0 = 10 份股份
每次加入现金后,我们都会增加股份数量:
new_fund_shares = 加入现金 / 基金价值
因为我们每次添加100.0货币单位且没有执行任何操作:
- ``100.0 / 100.0 = 1 share``` ```py Notice that the *fundvalue* remains unchanged. Quickly forwarding to the end of the year we have the following: * Starting net-asset-value: `1000` * Final net-asset-value: `2200` * Starting fundvalue = `100` * Final fundvalue = `100` * Starting number of shares: `10` * Final number of shares: `22` Now if we calculate the returns using the starting and ending *fundvalues* and because they are the same we have a: `0%` which matches the reality. because cash additions have not changed ## Using *fund tracking* in backtrader ### Adding cash First, the broker has gained a method to canonically add cash to the system:
add_cash(cash)
Using it inside the strategy for example:
`def next(self):
如果条件成立: self.broker.add_cash(1000.0)`
This method **MUST** be used to track the entry and exit of cash into the system and properly track the fund value. ### Automatic Activate it in the *broker*:
`…
cerebro.broker.set_fundmode(True)
…`
changing at the same time the default fund start value:
`…
cerebro.broker.set_fundmode(True, 10.0) # 默认为 100
…`
or in independent calls:
`…
cerebro.broker.set_fundmode(True)
cerebro.broker.set_fundstartval(10.0) # 默认为 100
…`
After activation of the default mode and coming back to the `TimeReturn` analyzer examples from above:
`…
1
cerebro.addanalyzer(bt.analyzers.TimeReturn) # 自动检测经纪人模式
2
cerebro.addanalyzer(bt.analyzers.TimeReturn, fund=True) # 追踪基金价值
3
cerebro.addanalyzer(bt.analyzers.TimeReturn, fund=False) # 追踪净资产价值
…`
`1` and `2` are equivalent. But one should go for `1`. If one wishes to compare, one can always force the `TimeReturn` analyzer to not use the *fundvalue* and rather track the *net-asset-value* An example is worth a thousand words. In the sample, we’ll be using doing as described above but with some extra cash (the asset has a per-share value over `3000`). The initial cash level will be `10000`, the default in *backtrader* and on the *15^(th)* of each month, `1000` extra monetary units will be added (using a recurring `Timer`). It will be 24 months (which is the size of the standard data sample used in *backtrader*) #### Without any operations
$ ./fund-tracker.py --broker fundmode=True --strat cash2add=1000 --cerebro writer=True --plot
The graphical view  And the text output (capped for readability):
`- timereturn:
... - 基金:无
- 分析:
- 2005-12-31: 0.0
- 2006-12-31: 0.0
…
- timereturn1:
- 参数: ... - 基金:真
- 分析:
- 2005-12-31: 0.0
- 2006-12-31: 0.0
…
- timereturn2:
... - 基金:假
- 分析:
- 2005-12-31: 1.2
- 2006-12-31: 0.545454545455`
There are 3 `TimeReturn` analyzers getting added. * The 1^(st) has `fund=None` (default) which means to track the actual `fundmode` set in the broker (in this case `True`) It says that the yearly returns were `0.0` and `0.0`. Since we made no operations: **Ok** * The 2^(nd) has `fund=True` which means to use the *fundvalue* always It says that the yearly returns were `0.0` and `0.0`. Since we made no operations: **Ok** * The 3^(rd) has `fund=False` which means to use the *net-asset-value* always It says that the yearly returns were `1.2` (*120%*) and `0.54` (*54%*). Since we made no operations: **This is clearly wrong** The plot contains also the 2 new *Observers* (`FundValue` and `FundShares`) which allow to see how even if the *net-asset-value* grows with the addition of cash every month, the *fundvalue* remains constant as `100.0`. At the same times the shares grow with each cash addition. #### Let’s trade The same as above but with some trading using a standard moving average crossover
$ ./fund-tracker.py --broker fundmode=True --strat cash2add=1000,trade=True --cerebro writer=True --plot
The graphical view  And the text output (capped for readability):
`- timereturn:
... - 基金:无
- 分析: - 2005-12-31:-0.00642229824537 - 2006-12-31:7.78998679263e-05 ....................................................................... - timereturn1: ... - 基金:真
- 分析:
- 2005-12-31:-0.00642229824537
- 2006-12-31:7.78998679263e-05
…
- timereturn2:
... - 基金:假
- 分析:
- 2005-12-31:1.19378185337
- 2006-12-31:0.546479045423`
The same three `TimeReturn` analyzers from before. The ones with `fund=None` and `fund=True` give reasonable results whereas the one using `fund=False` is clearly off the chart again with `119%` and `54%`, which is clearly not the return offered by the moving average crossover. ### Manual In this case (which is the default in the broker and even if the broker is tracking the value of the fund, only those analyzers with `fund=True` will use the value. A quick run with only the textual ouput:
$ ./fund-tracker.py --strat cash2add=1000,trade=True --cerebro writer=True
Output:
`- timereturn:
... - 基金:无
- 分析:
- 2005-12-31:1.19378185337
- 2006-12-31:0.546479045423
…
- timereturn1:
... - 基金:真
- 分析:
- 2005-12-31:-0.00642229824537
- 2006-12-31:7.78998679263e-05
…
- timereturn2:
... - 基金:假
- 分析:
- 2005-12-31:1.19378185337
- 2006-12-31:0.546479045423`
Now only the `TimeReturn` with `fund=True` delivers sensible results. ## Conclusion The new `fundmode` implemented in the broker and which can be used (automatically/manually) in the analyzers, allows to use *backtrader* to model the inner workings of a real fund or use cases like constant investment of money at given intervals. ## Sample Usage
`$ ./fund-tracker.py --help
用法:fund-tracker.py [-h] [–data0 DATA0] [–fromdate FROMDATE]
[--todate TODATE] [--cerebro kwargs] [--broker kwargs] [--sizer kwargs] [--strat kwargs] [--plot [kwargs]]
BackTrader 中文文档(十六)(2)https://developer.aliyun.com/article/1505375