当前位置:网站首页>One article of the quantification framework backtrader read observer
One article of the quantification framework backtrader read observer
2022-06-26 14:16:00 【Zhuge said talk】
brief introduction
Backtrader observer The observer is mainly used to observe each state index during the operation of the strategy , Such as funds 、 Trading point, etc , Calling cerebro.plot() After that, it can easily visualize the changes of status indicators , As shown in the figure below Broker、Trades and BuySell 3 individual observer Observers can be used to look at cash and market value 、 Trading profit and loss as well as the change of trading point in the back testing process .

Usage method
adopt cerebro.addobserver() add to observer The observer
import backtrader as bt
# View revenue series
cerebro.addobserver(bt.observers.TimeReturn)
# View the fallback sequence
cerebro.addobserver(bt.observers.DrawDown)
addobserver(obscls, args, **kwargs): Parameters obscls Corresponding observer The observer ,args, **kwargs Corresponding to the parameters supported by the observer
cerebro = bt.Cerebro(stdstats=False)
cerebro.addobserver(bt.observers.Broker)
cerebro.addobserver(bt.observers.Trades)
cerebro.addobserver(bt.observers.BuySell)
cerebro Will default to add Broker(Cash & Value)、Trades、BuySell 3 An observer (stdstats=True), You can instantiate cerebro when , adopt bt.Cerebro(stdstats=False) To control the default display
observers Observer execution time : observers The observer is in all indicators and strategies next Method is run and the data is counted , So in strategy next Read in the method observer The latest data [0] be relative to next The current moment of is a little late bar Of
How to read observer Data in the observer
observers The observer belongs to lines object , Historical back test data is stored , It can be like the market lines Object . Policy properties self.stats To visit observers The observer
class MyStrategy(bt.Strategy):
def next(self):
# Available cash of the previous day at the current time point
self.stats.broker.cash[0]
self.stats.broker.value[0]
# Get the benefit of the day before the current moment
self.stats.timereturn.line[0]
How to save observer Data in the observer
backtrader Currently there is no direct save observer Observer data to file mechanism , We need to do it ourselves .backtrader The recommended implementation method is :
At the strategic level start Method
At the strategic level next、stop Method
With DrawDown The observer mode is an example , The sample code is as follows :
class MyStrategy(bt.Strategy):
def start(self):
self.mystats = open('mystats.csv', 'wb')
self.mystats.write('datetime,drawdown, maxdrawdown\n')
def next(self):
self.mystats.write(self.data.datetime.date(-1).strftime('%Y-%m-%d'))
self.mystats.write(',%.2f' % self.stats.drawdown.drawdown[0])
self.mystats.write(',%.2f' % self.stats.drawdown.maxdrawdown[0])
self.mystats.write('\n')
def stop(self):
self.mystats.write(self.data.datetime.date(0).strftime('%Y-%m-%d'))
self.mystats.write(',%.2f' % self.stats.drawdown.drawdown[0])
self.mystats.write(',%.2f' % self.stats.drawdown.maxdrawdown[0])
self.mystats.write('\n')
backtrader Self contained observer The observer
Self contained observers Observer yes :
Benchmark: A revenue series that records performance benchmarks , Performance benchmark data must be passed in advance adddata、resampledata、replaydata And so on cerebro, During visualization, the revenue series of the strategy itself and the revenue curve of the performance benchmark will be drawn at the same time
Broker、Cash、Value: Broker The observer records the broker broker Available funds and total assets at each point in time , Visualization will also show cash and values curve ; If you want to show it separately cash and values, Can be called separately backtrader.observers.Cash and backtrader.observers.Value
BuySell: The buy and sell signals during the back test are recorded , During visualization, the buying and selling points will be marked on the price curve
DrawDown: The fallback sequence of the backtesting process is recorded , Draw the fallback curve during visualization
TimeReturn: The return series in the back testing process is recorded , When visualizing, it will draw TimeReturn The yield curve
Trades: The profit and loss of each transaction in the back test process are recorded , Profit and loss points will be drawn during visualization
LogReturns: The policy is documented log Return
LogReturns2: Expanded LogReturns Support 2 Data ,data0 and data1
FundValue: Record the results of the back test fund value
FundShares: Record the results of the back test fund share
among , frequently-used observers Observer yes :Broker、BuySell、Trades、TimeReturn、DrawDown、Benchmark etc. .
newly build observers The observer
Broker Observer yes 2 individual lines object :cash、value. The implementation is similar to the following :
class Broker(Observer):
alias = ('CashValue',)
lines = ('cash', 'value')
plotinfo = dict(plot=True, subplot=True)
def next(self):
self.lines.cash[0] = self._owner.broker.getcash()
self.lines.value[0] = value = self._owner.broker.getvalue()
It can be seen that , Customize observer The observer steps are as follows :
Customize observer The observer is inherited from bt.observer.Observer; You can also inherit that you have other observers
Declare what is needed lines And parameters , Parameters can be chosen . stay next Method
Statement plotinfo、plotlines attribute , be used for cerebro.plot() Visual display
There is an automatic attribute _owner Means holding the observer The strategy of
further , We can customize it OrderObserver( Refer to the official website ): The standard BuySell The observer only cares about the operations that have been performed , We can create one observer Observers view order creation and expiration , As shown below .
class OrderObserver(bt.observer.Observer):
lines = ('created', 'expired',)
plotinfo = dict(plot=True, subplot=True, plotlinelabels=True)
plotlines = dict(
created=dict(marker='*', markersize=8.0, color='lime', fillstyle='full'),
expired=dict(marker='s', markersize=8.0, color='red', fillstyle='full')
)
def next(self):
for order in self._owner._orderspending:
if order.data is not self.data:
continue
if not order.isbuy():
continue
# Only interested in "buy" orders, because the sell orders
# in the strategy are Market orders and will be immediately
# executed
if order.status in [bt.Order.Accepted, bt.Order.Submitted]:
self.lines.created[0] = order.created.price
elif order.status in [bt.Order.Expired]:
self.lines.expired[0] = order.created.price
Of course , We can also inherit from other existing observers , Reference code :
class MyBuySell(bt.observers.BuySell):
# take barplot The default value is changed to True
params = (('barplot', True), ('bardist', 0.015))
# Change triangle to arrow
plotlines = dict(
buy=dict(marker=r'$\Uparrow$', markersize=8.0, color='#d62728' ),
sell=dict(marker=r'$\Downarrow$', markersize=8.0, color='red')
)
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 investment exchange group 、 Quantitative investment seminar group , With many investment lovers 、 Quantitative practitioners 、 Technical leaders communicate with each other 、 Compare notes , Quickly improve your investment level .
It's not easy to write , If you think this article can help you , Help me. Let's see .
Reference resources
边栏推荐
- "Scoi2016" delicious problem solution
- How to call self written functions in MATLAB
- Exercises under insect STL string
- C language | the difference between heap and stack
- 9項規定6個嚴禁!教育部、應急管理部聯合印發《校外培訓機構消防安全管理九項規定》
- 同花顺股票开户选哪个证券公司是比较好,比较安全的
- 7.consul service registration and discovery
- In insect classes and objects
- Correlation analysis related knowledge
- 9项规定6个严禁!教育部、应急管理部联合印发《校外培训机构消防安全管理九项规定》
猜你喜欢

Calculate the distance between two points (2D, 3D)

Reprint - easy to use wechat applet UI component library

FreeFileSync 文件夹比较与同步软件

Sword finger offer 09.30 Stack

数学建模经验分享:国赛美赛对比/选题参考/常用技巧

New specification of risc-v chip architecture

Variable declaration of typescript

A must for programmers, an artifact utools that can improve your work efficiency n times

Global variable vs local variable

array
随机推荐
d检查类型是指针
MySQL | basic commands
微信小程序注册指引
Introduction to granular computing
虫子 内存管理 上
ICML 2022 | LIMO: 一种快速生成靶向分子的新方法
Assert and constd13
Solutions to the failure of last child and first child styles of wechat applet
C language | the difference between heap and stack
【HCSD应用开发实训营】一行代码秒上云评测文章—实验过程心得
PHP非对称加密算法(RSA)加密机制设计
近期比较重要消息
windows版MySQL软件的安装与卸载
Research on balloon problem
Formal parameters vs actual parameters
Sword finger offer 09.30 Stack
Generation and rendering of VTK cylinder
数学建模经验分享:国赛美赛对比/选题参考/常用技巧
Pytorch based generation countermeasure Network Practice (7) -- using pytorch to build SGAN (semi supervised GaN) to generate handwritten digits and classify them
Pointer