当前位置:网站首页>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
边栏推荐
- Assert and constd13
- Freefilesync folder comparison and synchronization software
- Is expression of D
- 33. Use rgbd camera for target detection and depth information output
- [wc2006] director of water management
- 永远不要使用Redis过期监听实现定时任务!
- Select tag - uses the default text as a placeholder prompt but is not considered a valid value
- Niuke challenge 53:c. strange magic array
- Wechat applet SetData dynamic variable value sorting
- Linear basis
猜你喜欢

Wechat applet -picker component is repackaged and the disabled attribute is added -- below

Cloudcompare - Poisson reconstruction

Pointer

Postman自动化接口测试

Installation and uninstallation of MySQL software for windows

Wechat applet -picker component is repackaged and the disabled attribute is added -- above

Sword finger offer 10 Ⅰ 10Ⅱ. 63 dynamic planning (simple)

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

Usage of unique function

7.Consul服务注册与发现
随机推荐
d的is表达式
【系统分析师之路】第十五章 复盘数据库系统(数据库案例分析)
Is it safe to open a securities account? Is there any danger
Is expression of D
Luogu p4145 seven minutes of God created questions 2 / Huashen travels around the world
Wechat applet SetData dynamic variable value sorting
Original code, inverse code and complement code
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
免费的机器学习数据集网站(6300+数据集)
Related knowledge of libsvm support vector machine
Jenkins build prompt error: eacces: permission denied
ThreadLocal giant pit! Memory leaks are just Pediatrics
Practice with the topic of bit operation force deduction
虫子 STL string上
Niuke challenge 53:c. strange magic array
Pointer
9 regulations and 6 prohibitions! The Ministry of education and the emergency management department jointly issued the nine provisions on fire safety management of off campus training institutions
Global variable vs local variable
虫子 内存管理 上
[proteus simulation] Arduino uno key start / stop + PWM speed control DC motor speed