当前位置:网站首页>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
边栏推荐
- A must for programmers, an artifact utools that can improve your work efficiency n times
- DOS command
- Half search, character array definition, character array uses D11
- 虫子 STL string上
- Never use redis expired monitoring to implement scheduled tasks!
- 团队管理的最关键因素
- How to check if a text field is empty or not in swift
- 免费的机器学习数据集网站(6300+数据集)
- C | analysis of malloc implementation
- [hcsd application development training camp] one line of code second cloud evaluation article - experience from the experiment process
猜你喜欢

ICML 2022 | LIMO: 一种快速生成靶向分子的新方法
![[MySQL from introduction to mastery] [advanced part] (II) representation of MySQL directory structure and tables in the file system](/img/03/a1885e4740bbfdbdee2446e3dd81d0.png)
[MySQL from introduction to mastery] [advanced part] (II) representation of MySQL directory structure and tables in the file system

BP neural network for prediction

2021-10-18 character array

ArcGIS cannot be opened and displays' because afcore cannot be found ' DLL, solution to 'unable to execute code'

FreeFileSync 文件夹比较与同步软件

9 articles, 6 interdits! Le Ministère de l'éducation et le Ministère de la gestion des urgences publient et publient conjointement neuf règlements sur la gestion de la sécurité incendie dans les établ

Pointer

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

C language | file operation and error prone points
随机推荐
Hands on data analysis unit 3 model building and evaluation
C language | file operation and error prone points
[hcsd application development training camp] one line of code second cloud evaluation article - experience from the experiment process
Zero basics of C language lesson 7: break & continue
常用控件及自定义控件
7.consul service registration and discovery
Svn commit error after deleting files locally
Generation and rendering of VTK cylinder
In insect classes and objects
C | analysis of malloc implementation
9 articles, 6 interdits! Le Ministère de l'éducation et le Ministère de la gestion des urgences publient et publient conjointement neuf règlements sur la gestion de la sécurité incendie dans les établ
程序员必备,一款让你提高工作效率N倍的神器uTools
Calculate the distance between two points (2D, 3D)
[MySQL from introduction to mastery] [advanced part] (II) representation of MySQL directory structure and tables in the file system
mysql配置提高数据插入效率
Installation tutorial about origin2019
Zero basics of C language lesson 8: Functions
Linear basis
近期比较重要消息
D中不用GC