1. 程式人生 > 實用技巧 >Backtrader中文筆記之 Strategy

Backtrader中文筆記之 Strategy

Strategy

A Cerebro instance is the pumping heart and controlling brain of backtrader. A Strategy is the same for the platform user.

Cerebro例項是backtrader的跳動心臟和控制的大腦。對於平臺使用者,策略是相同的

The Strategy’s expressed lifecycle in methods

策略的生命週期用方法表示

Note

A strategy can be interrupted during birth by raising a StrategySkipError

exception from the module backtrader.errors

在一個策略的生成過程中,可以通過從backtrader.errors模組中丟擲一個StrategySkipError異常來中斷策略

This will avoid going through the strategy during a backtesting. See the section Exceptions

這裡將避免在回測階段使用該策略。參見異常章節

  1. Conception: __init__

    This is obviously invoked during instantiation: indicators

    will be created here and other needed attribute. Example:

  2. 這裡很顯然是在例項化期間呼叫:這裡將建立指標和其他需要的屬性。
  3. def __init__(self):
        self.sma = btind.SimpleMovingAverage(period=15)
    
  4. Birth: start

  5. 懷孕:start

    The world (cerebro) tells the strategy is time to start kicking. A default empty method exists.

  6. cerebro告訴這個策略開始工作了。這是一個存在的預設的方法
  7. Childhood: prenext

  8. 兒童:prenext

    indicators declared during conception will have put constraints on how long the strategy needs to mature: this is called the minimum period. Above __init__ created a SimpleMovingAverage with a period=15.

  9. 設計期間公佈的指標將限制戰略成熟的時間:這被稱為最小週期。在__init__創造了一個SimpleMovingAverage,period=15。

    As long as the system has seen less than 15 bars, prenext will be called (the default implementation is a no-op)

  10. 只要系統看到的bar少於15個,prenext就會被呼叫(預設實現是no-op)
  11. Adulthood: next

  12. 成人:next

    Once the system has seen 15 bars and the SimpleMovingAverage has a buffer large enough to start producing values, the strategy is mature enough to really execute.

    There is a nextstart method which is called exactly once, to mark the switch from prenext to next. The default implementation of nextstart is to simply call next

  13. 一旦系統達到15條,並且SimpleMovingAverage擁有足夠大的緩衝區來開始產生價值,那麼該策略就足夠成熟,可以真正執行了。

    有一個nextstart方法,它只被呼叫一次,用於標記從prenext到next的切換。nextstart的預設實現只是呼叫next
  14. Reproduction: None

  15. 再生產:None

    Ok, strategies do not really reproduce. But in a sense they do, because the system will instantiate them several times if optimizing (with different parameters)

  16. 好吧,策略是不會重現的。但從某種意義上說,它們確實如此,因為如果優化(使用不同的引數),系統將對它們進行多次例項化。
  17. Death: stop

    The system tells the strategy the time to come to a reset and put things in order has come. A default empty method exists.

  18. 死亡:stop
  19. 系統告訴策略,重啟和整理的時間已經到來。存在一個預設的空方法。

In most cases and for regular usage patterns this will look like:

在大多數情況下,對於常規的使用模式,這看起來像:

class MyStrategy(bt.Strategy):

    def __init__(self):
        self.sma = btind.SimpleMovingAverage(period=15)

    def next(self):
        if self.sma > self.data.close:
            # Do something
            pass

        elif self.sma < self.data.close:
            # Do something else
            pass

In this snippet:

在這個程式碼片段:

  • During __init__ an attribute is assigned an indicator

  • 在__init__期間,屬性被分配一個指示符
  • The default empty start method is not overriden

  • 預設的空start方法沒有被覆蓋
  • prenext and nexstart are not overriden

  • prenext和nexstart沒有被覆蓋
  • In next the value of the indicator is compared against the closing price to do something

  • 接下來,將指標的值與收盤價進行比較,以完成某項操作
  • The default empty stop method is not overriden

  • 預設的空stop方法沒有被覆蓋

Strategies, like a trader in the real world, will get notified when events take place. Actually once per next cycle in the backtesting process. The strategy will:

策略就像現實世界中的交易者一樣,在事件發生時得到通知。實際上是在回測過程的下一個迴圈中。戰略將:

  • be notified through notify_order(order) of any status change in an order

  • 通過notify_order(order)通知訂單中的任何狀態更改
  • be notified through notify_trade(trade) of any opening/updating/closing trade

  • 通過notify_trade(trade)通知任何開始/更新/結束的交易
  • be notified through notify_cashvalue(cash, value) of the current cash and portfolio in the broker

  • 通過notify_cashvalue(現金,價值)通知經紀人的當前現金和投資組合
  • be notified through notify_fund(cash, value, fundvalue, shares) of the current cash and portfolio in the broker and tradking of fundvalue and shares

  • 通過notify_fund(現金、價值、基金價值、股份)通知經紀人的當前現金和投資組合以及基金價值和股份的交易
  • Events (implementation specific) via notify_store(msg, *args, **kwargs)

  • 事件(具體實現)通過notify_store(msg, *args, **kwargs)

    See Cerebro for an explanation on the store notifications. These will delivered to the strategy even if they have also been delivered to a cerebro instance (with an overriden notify_store method or via a callback)

  • 有關商店通知的解釋,請參閱大腦。即使它們也已被傳遞到cerebro例項(使用重寫的notify_store方法或通過回撥)也會傳遞到策略中

And Strategies also like traders have the chance to operate in the market during the next method to try to achieve profit with

而策略也像交易者一樣,有機會在市場中操作下一個方法,試圖獲得利潤

  • the buy method to go long or reduce/close a short position

  • 做多或減/平空頭的買入方法
  • the sell method to go short or reduce/close a long position

  • 賣空或減少/平倉多頭的賣出方法
  • the close method to obviously close an existing position

  • 明顯是關閉現有位置的關閉方法
  • the cancel method to cancel a not yet executed order

  • cancel方法取消尚未執行的訂單

How to Buy/Sell/Close

The Buy and Sell methods generate orders. When invoked they return an Order (or subclass) instance that can be used as a reference. This order has a unique ref identifier that can be used for comparison

Buy和Sell方法生成訂單。當被呼叫時,它們返回一個可以用作引用的Order(或子類)例項。此訂單具有可用於比較的唯一ref識別符號

Note

Subclasses of Order for speficic broker implementations may carry additional unique identifiers provided by the broker.

特定代理實現的Order子類可以攜帶代理提供的其他唯一識別符號。

To create the order use the following parameters:

Buy和Sell方法生成訂單。當被呼叫時,它們返回一個可以用作引用的Order(或子類)例項。此訂單具有可用於比較的唯一ref識別符號

注意

特定代理實現的Order子類可以攜帶代理提供的其他唯一識別符號。

要建立訂單,請使用以下引數:

  • data (default: None)

    For which data the order has to be created. If None then the first data in the system, self.datas[0] or self.data0 (aka self.data) will be used

  • 必須為其選擇建立訂單的資料。如果沒有,那麼系統中的第一個資料,self.datas[0] or self.data0(又名self.data)將被使用
  • size (default: None)

    Size to use (positive) of units of data to use for the order.

    If None the sizer instance retrieved via getsizer will be used to determine the size.

  • 為訂單使用的資料單位的大小(正)。

    如果沒有,那麼通過getsizer獲取的sizer例項將用於確定大小。
  • price (default: None)

    Price to use (live brokers may place restrictions on the actual format if it does not comply to minimum tick size requirements)

  • 使用價格(如果實際格式不符合最小刻度大小要求,實時經紀人可能會對實際格式進行限制)
  • None is valid for Market and Close orders (the market determines the price)

  • 對市場和平倉指令無效(市場決定價格)
  • For Limit, Stop and StopLimit orders this value determines the trigger point (in the case of Limit the trigger is obviously at which price the order should be matched)

  • 對於Limit, Stop和StopLimit指令,這個值決定了觸發點(在Limit的情況下,觸發點顯然是該指令應該匹配的價格)。
  • plimit (default: None)

    Only applicable to StopLimit orders. This is the price at which to set the implicit Limit order, once the Stop has been triggered (for which price has been used)

  • 僅適用於StopLimit指令。這是觸發止損後設置隱含限價單的價格(已使用價格)
  • exectype (default: None)

    Possible values:

    • Order.Market or None. A market order will be executed with the next available price. In backtesting it will be the opening price of the next bar

    • Order.Market or None.。市場訂單將以下一個可用價格執行。在回溯測試中,它將是下一個bar的開盤價
    • Order.Limit. An order which can only be executed at the given price or better

    • Order.Limit.只能以給定價格或更好價格執行的訂單
    • Order.Stop. An order which is triggered at price and executed like an Order.Market order

    • Order.Stop.以價格觸發並執行訂單,感覺像5檔成交
    • Order.StopLimit. An order which is triggered at price and executed as an implicit Limit order with price given by pricelimit

    • 以價格觸發並作為隱含限價指令執行的指令,價格由pricelimit給出
  • valid (default: None)

    Possible values:

    • None: this generates an order that will not expire (aka Good til cancel) and remain in the market until matched or canceled. In reality brokers tend to impose a temporal limit, but this is usually so far away in time to consider it as not expiring

    • 這將生成一個不會過期的訂單(也就是在取消之前的好訂單),並且在匹配或取消之前保持在市場中。在現實中,經紀人往往會設定一個時間限制,但這通常是如此遙遠,以至於認為它不會到期
    • datetime.datetime or datetime.date instance: the date will be used to generate an order valid until the given datetime (aka good til date)

    • Order.DAY or 0 or timedelta(): a day valid until the End of the Session (aka day order) will be generated

    • numeric value: This is assumed to be a value corresponding to a datetime in matplotlib coding (the one used by backtrader) and will used to generate an order valid until that time (good til date)

  • tradeid (default: 0)

    This is an internal value applied by backtrader to keep track of overlapping trades on the same asset. This tradeid is sent back to the strategy when notifying changes to the status of the orders.

  • **kwargs: additional broker implementations may support extra parameters. backtrader will pass the kwargs down to the created order objects

    Example: if the 4 order execution types directly supported by backtrader are not enough, in the case of for example Interactive Brokers the following could be passed as kwargs:

    orderType='LIT', lmtPrice=10.0, auxPrice=9.8
    

    This would override the settings created by backtrader and generate a LIMIT IF TOUCHED order with a touched price of 9.8 and a limit price of 10.0.