当前位置:网站首页>One article of quantitative framework backtrader: understand indicator indicators
One article of quantitative framework backtrader: understand indicator indicators
2022-07-24 17:05:00 【Zhuge said talk】
brief introduction
The previous series of articles have covered SMA、EMA、MACD、KDJ、RSI、BOLL And other technical indicators , Not seen yet , It is recommended to follow the official account to check .
Backtrader The framework has built-in more than 100 technical analysis indicators , Packaged in backtrader.indicators In bag , It can greatly reduce the development cost , Improve the speed of strategy iteration .
Usage method
Indicators Indicators can be used in 2 A place to : One is to use ; The other is to use in other indicators .
backtrader It is very easy to use built-in indicators , just :
At the strategic level __init__ Instantiate the corresponding indicator in the method
stay next Method to use or check the corresponding index value or its derived value
Here is SMA Examples of using simple moving average indicators .
import backtrader as bt
class MyStrategy(bt.Strategy):
params = (('period', 20),)
def __init__(self):
self.sma = bt.indicators.SMA(self.data, period=self.p.period)
...
def next(self):
if self.sma[0] > self.data.close[0]:
self.buy()
It should be noted that :
__init__ Any index declared in the method will be in next Calculate before method call
stay __init__ Method for lines Any operation of the object will generate other line object (python operators overloading overriding), And in the next Method generates regular python type , Such as floats or bools
__init__ Method is faster , At the same time, it can make next The logic of the method is simpler
__init__ Method does not support partial python The operator , Need to use bt Built in functions to handle , Such as bt.And, bt.Or, bt.All, bt.Any. In addition to these ,backtrader It also provides bt.Cmp, bt.If, bt.Max, bt.Min, bt.Sum, bt.DivByZero Such as function
backtrader The list of supported native indicators can be viewed on the official website :Indicators - Reference - Backtrader
It should be noted that backtrader It also supports indicator aliases , Such as SMA Or you could write it as MovingAverageSimple or SimpleMovingAverage
MovingAverageSimple
Alias:
SMA, SimpleMovingAverage
Non-weighted average of the last n periods
Formula:
movav = Sum(data, period) / period
Use TA-Lib
although backtrader With many indicators , It is also easier to add new indicators . But because of TA-lib Widely used , Everyone trusts it ,backtrader It is also integrated. TA-Lib.
import backtrader as bt
class MyStrategy(bt.Strategy):
params = (('period', 20),)
def __init__(self):
self.sma = bt.talib.SMA(self.data, timeperiod=self.p.period)
...
...
It's on it backtrader Use in talib Medium SMA Example , It can be seen that there is little difference in the use method .
adopt print(bt.talib.SMA.__doc__) You can view the help documentation .
>>> print(bt.talib.SMA.__doc__)
SMA([input_arrays], [timeperiod=30])
Simple Moving Average (Overlap Studies)
Inputs:
price: (any ndarray)
Parameters:
timeperiod: 30
Outputs:
real
backtrader Supported by talib The index list can be viewed on the official website :Indicators - ta-lib - Reference - Backtrader
Custom metrics
# Inherited from bt.Indicator Or other existing indicator classes
class DummyInd(bt.Indicator):
# Define held lines, Need at least 1 individual line
lines = ('dummyline',)
# params Parameters can be chosen
params = (('value', 5),)
# plotinfo Optional , Used to control drawing behavior
plotinfo = dict(subplot=False)
# __init__ Method or next Method required
def __init__(self):
self.lines.dummyline = bt.Max(0.0, self.params.value)
This indicator in the sample code will output 0.0, Or is it self.params.value, Depending on self.params.value Is it greater than 0.0.
In addition to the __init__ Method implementation , It can also be in next Method to achieve index calculation , As shown below .
def next(self):
self.lines.dummyline[0] = max(0.0, self.params.value)
Except for efficiency 、 Readability , When it comes to peroid Minimum cycle ,next Methods need to be handled by yourself ,__init__ Methods do not require special treatment . So the best way is __init__ Method , If it doesn't work , Just consider in next Method . You can also use once Method runonce Mode for computational optimization .
Indicator Visualization

If the program calls cerebro.plot, that
All declared indicators will be automatically plotted
Operation generated lines Objects will not be drawn , Such as
close_over_sma = self.data.close > self.smaIf you want to draw the lines object , have access to
LinePlotterIndicatorclass ,name Parameters are held by this indicator line name
close_over_sma = self.data.close > self.sma
LinePlotterIndicator(close_over_sma, name='Close_over_SMA')
Can pass plotinfo Declaration to control the drawing of indicators .plotinfo It can be tuple、dict or OrderedDict.
class MyIndicator(bt.Indicator):
....
plotinfo = dict(subplot=False)
....
# You can set it separately after instantiation
myind = MyIndicator(self.data, someparam=value)
myind.plotinfo.subplot = True
# You can also set when instantiating
myind = MyIndicator(self.data, someparams=value, subplot=True)
plotinfo The parameter list of is :plot( Whether to draw , The default is True),subplot( Whether to draw in a separate window , The default is True,MA Class index this parameter is False),plotname( Index map name , Default to indicator class name ),plotabove( The plot position is above the data , The default is False),plotlinelabels, plotymargin, plotyticks,plothlines, plotyhlines, plotforce.
Conclusion & communication
Pay attention to WeChat public number : Zhuge said talk, Get more . At the same time, you can also get an invitation to join the quantitative investment seminar group , With many practitioners 、 Technical leaders communicate with each other 、 Compare notes , Quota co., LTD. , Don't miss .
It's not easy to write , If you think this article can help you , Help point like forward appreciation , Let the author have the motivation to insist on writing a good article .
Reference resources
边栏推荐
- 量化框架backtrader之一文读懂Indicator指标
- Sword finger offer 48. the longest substring without repeated characters
- Why should we launch getaverse?
- QT embed Notepad under win10
- The third edition of New Horizon College English reading and Writing Tutorial 4 graduation examination site (units 1,2,3,5,6)
- JSP custom tag library --foreach
- I'll teach you how to use NPs to build intranet penetration services. When you go out, you can easily connect your lightweight notebook to your home game console to play remotely
- QT graphical interface beginner project - unmanned aerial vehicle group combat simulation
- Matlab writes excel string and number merging
- 快速入门
猜你喜欢

Comparison of array and object merging methods assign, merge, defaults, defaultsdeep in lodash

查数据库实际数据增长情况

EF LINQ Miscellany

At & T pseudo instruction and interpretation of CFI CFA

CDN(Content Delivery Network)内容分发网络从入门到与实战

PS pull out logo

Coldplay weekly issue 10

CPU comparison

快速入门

Sword finger offer 22. the penultimate node in the linked list
随机推荐
Sword finger offer 48. the longest substring without repeated characters
Summary of ROS master-slave communication experience
剑指 Offer 25. 合并两个排序的链表
Zhao Ming, CEO of glory: it is difficult for a single manufacturer to achieve full scene product coverage
Cann training camp learns the animation stylization and AOE ATC tuning of the second season of 2022 model series
GDB online debugging of work notes
Why should we launch getaverse?
The orders in the same city are delivered in the same city, and the order explosion is still handy!
Canvas from getting started to persuading friends to give up (graphic version)
Wechat applet list (list rendering of data rendering)
SS-Paper【1】:Fully Convolutional Networks for Semantic Segmentation
IP第十三天笔记
[redis] -1. two ways of setting up environment based on docker
什么是模糊理论,基础,流程
portfwd 端口转发
PAT甲级——签到与签出
Meeting OA project progress (II)
JSP custom tag library --foreach
Zcmu--5083: number pairs of ly (C language)
AXI协议(2):AXI架构的五个通道和两种事务