在backtrader 社區中 ,傾向於重複的事情是,用戶解釋了複製在例如 TradingView 中獲得的回溯測試結果的意願,這些天非常流行,或者其他一些回溯測試平臺。
在不真正瞭解TradingView中使用的語言(命名Pinescript)並且對回溯測試引擎內部進行零公開的情況下,仍然有一種方法可以讓使用者知道,跨平臺編碼必須加緊鹽。
指標:並不總是忠於來源
當為 backtrader實施新指標時,無論是直接用於分發還是作為網站的片段,都非常重視原始定義。這是RSI 一個很好的例子。
-
威爾斯·懷爾德設計了
RSI使用Modified Moving Average(又名Smoothed Moving Average,參見 維琪百科 - 修改後的移動平均線 ) -
儘管如此,許多平臺還是為使用者提供了一些稱為經典
RSIExponential Moving Average的東西,而不是書中所說的。 -
鑒於兩個平均值都是指數級的,差異並不大,但這不是Welles Wilder所定義的。它可能仍然有用,甚至可能更好,但它不是
RSI.文件(如果可用)沒有提到這一點。
in backtrader 的預設配置RSI是使用 MMA 忠實於源,但要使用的移動平均線是一個參數,可以通過子類化或在運行時實例化期間更改為使用EMA甚至簡單移動平均線。
例如:頓奇安海峽
維琪百科的定義:維琪百科 - Donchian頻道 )。它只是文本,它沒有提到使用通道突破作為交易信號。
另外兩個定義:
這兩個引用明確指出,用於計算通道的數據不包括當前柱,因為如果它包含...突破不會被反映出來。這是來自股票圖表的示例圖表
現在轉到TradingView。首先是連結
以及該頁面的圖表。
甚至Investopedia也使用TradingView的圖表,顯示沒有突破。這裡: 投資百科 - 頓奇安頻道 - https://www.investopedia.com/terms/d/donchianchannels.asp
正如有些人所說...起泡的藤壺!!!!。因為在 TradingView 圖表 中看不到 突破。這意味著指標的實現是使用 當前 價格柱來計算通道。
backtrader的頓奇安海峽
標準backtrader發行版中沒有DonchianChannels實現,但可以快速製作。參數將是當前柱是否用於通道計算的決定因素。
class DonchianChannels(bt.Indicator):
'''
Params Note:
- ``lookback`` (default: -1)
If `-1`, the bars to consider will start 1 bar in the past and the
current high/low may break through the channel.
If `0`, the current prices will be considered for the Donchian
Channel. This means that the price will **NEVER** break through the
upper/lower channel bands.
'''
alias = ('DCH', 'DonchianChannel',)
lines = ('dcm', 'dch', 'dcl',) # dc middle, dc high, dc low
params = dict(
period=20,
lookback=-1, # consider current bar or not
)
plotinfo = dict(subplot=False) # plot along with data
plotlines = dict(
dcm=dict(ls='--'), # dashed line
dch=dict(_samecolor=True), # use same color as prev line (dcm)
dcl=dict(_samecolor=True), # use same color as prev line (dch)
)
def __init__(self):
hi, lo = self.data.high, self.data.low
if self.p.lookback: # move backwards as needed
hi, lo = hi(self.p.lookback), lo(self.p.lookback)
self.l.dch = bt.ind.Highest(hi, period=self.p.period)
self.l.dcl = bt.ind.Lowest(lo, period=self.p.period)
self.l.dcm = (self.l.dch + self.l.dcl) / 2.0 # avg of the above
將與範例圖表一起使用lookback=-1 看起來像這樣(放大)
人們可以清楚地看到突破,而版本中沒有突破lookback=0 。
編碼影響
程式師首先進入商業平臺,並使用Donchian Channels實施策略。由於圖表不顯示突破,因此必須將當前價格值與之前的通道值進行比較。某物如
if price0 > channel_high_1:
sell()
elif price0 < channel_low_1:
buy()
當前價格,即:price0 正在與週期前的 high/low 通道值 1 進行比較(因此後 _1 綴)
作為一個謹慎的程式師,並且不知道 backtrader 中Donchian通道的實現預設為突破,代碼被移植並看起來像這樣
def __init__(self):
self.donchian = DonchianChannels()
def next(self):
if self.data[0] > self.donchian.dch[-1]:
self.sell()
elif self.data[0] < self.donchian.dcl[-1]:
self.buy()
這是錯誤的!!!因為突破發生在比較的同一時刻。正確的代碼:
def __init__(self):
self.donchian = DonchianChannels()
def next(self):
if self.data[0] > self.donchian.dch[0]:
self.sell()
elif self.data[0] < self.donchian.dcl[0]:
self.buy()
雖然這隻是一個小例子,但它顯示了回溯測試結果可能有何不同,因為指標已使用柱差進行1 編碼。它可能看起來不多,但是當錯誤的交易開始時,它肯定會有所作為。