Backtrader中文筆記之 Strategy - Sihnals
Strategy with Signals
Operating backtrader is also possible without having to write a Strategy. Although this is the preferred way, due to the object hierarchy which makes up the machinery, using Signals is also possible.
操作backtrader也可以不必編寫策略。儘管這是首選方法,但由於構成機械的物件層次結構,使用訊號也是可能的。Quick summary:
-
Instead of writing a Strategy
-
The end user add Signals (indicators anyhow) and the rest is done in the background
- 代替編寫一個策略類,例項化指標,編寫買/賣邏輯…
- 終端使用者新增訊號(指標),其餘的在後臺完成
import backtrader as bt data = bt.feeds.OneOfTheFeeds(dataname='mydataname') cerebro.adddata(data) cerebro.add_signal(bt.SIGNAL_LONGSHORT, MySignal) cerebro.run()
Of course the Signal itself is missing. Let’s define a very dumb Signal which yields:
當然,訊號本身已經消失了。讓我們定義一個非常啞的訊號,它會產生:
-
Long
indication if theclose
price is above a Simple Moving Average - 多頭指收盤價高於簡單移動平均線
-
Short
indication if theclose
price is below a Simple Moving Average - 收盤價低於簡單移動平均線時的空頭指示
The definition:
class MySignal(bt.Indicator): lines = ('signal',) params = (('period', 30),) def __init__(self): self.lines.signal = self.data - bt.indicators.SMA(period=self.p.period)
And now it is really done. When run
is executed Cerebro will take care of instantiating a special Strategy instance which knows what to do with the Signals.
現在它真的完成了。當執行執行時,Cerebro會例項化一個特殊的策略例項,該例項知道如何處理訊號。
Initial FAQ
問題
-
How is the volume of buy/sell operations determined?
A cerebro instance adds automatically a
FixedSize
sizer to strategies. The end user can change the sizer to alter the policy withcerebro.addsizer
-
How are orders executed?
The execution type is
Market
and the validity is Good Until Canceled
Signals technicalities
From a technical and theoretical point of view can be as described:
-
A callable that returns another object when called (only once)
This is in most cases the instantiation of a class, but must not be
-
Supports the
__getitem__
interface. The only requested key/index will be0
From a practical point of view and looking at the example above a Signal is:
-
A lines object from the backtrader ecosystem, mostly an Indicator
This helps when using other Indicators like when in the example the Simple Moving Average is used.
Signals indications
The signals delivers indications when queried with signal[0]
and the meaning is:
-
> 0
->long indication
-
< 0
->short indication
-
== 0
-> No indication
The example does simple arithmetic with self.data - SMA
and:
-
Issues a
long indication
when thedata
is above theSMA
-
Issues a
short indication
when thedata
is below theSMA