導入
バックテストを行う際、戦略の動作を知りたいことがよくあります。最終的な統計指標を通じてそれを垣間見ることはできますが、バックテストのプロセスを視覚化することが最も人間的です。同時に、観察することでより良い設計を行うこともできます。バックテストプロセスと定量的戦略を最適化します。Backtrader は matplotlib ライブラリを使用して視覚化機能を提供します
説明書
バックトレーダーのデータ視覚化は非常に簡単で、run() の後に plot() メソッドを呼び出すだけです。
cerebro.run()
cerebro.plot()
plot(self, plotter=None, numfigs=1, iplot=True, **kwargs)
メソッドの各パラメータの意味は次のとおりです。
-
plotter
: PlotScheme と、プロット プロパティを含むその派生クラス オブジェクト。デフォルトは None です。None の場合、デフォルトの PlotScheme オブジェクトがインスタンス化されます。 -
numfigs
: グラフを複数の画像に分割して表示します。デフォルトは 1 です。 -
iplot
: Jupyter Notebook での実行時に自動的にインライン プロットするかどうか。デフォルトは True です。jupyter で実行していない場合は、このパラメータを False に設定することをお勧めします。そうしないと問題が発生する可能性があります。 -
*kwargs
:args パラメータは、プロッタの属性値を変更するために使用されます。
視覚化構成を体系的に制御するには 2 つの方法があります。
-
以下に示すように、plot() メソッドの args パラメータを設定することで直接実行できます。
cerebro.plot(iplot=False,
style='candel', # 设置主图行情数据的样式为蜡烛图
plotdist=0.1, # 设置图形之间的间距
barup = '#ff9896', bardown='#98df8a', # 设置蜡烛图上涨和下跌的颜色
volup='#ff9896', voldown='#98df8a', # 设置成交量在行情上涨和下跌情况下的颜色
)
2. PlotScheme クラスをカスタマイズして、対応するパラメーターを変更します
PlotScheme オブジェクトには、以下に示すように、すべてのシステム レベルのプロット オプションが含まれています。
class PlotScheme(object):
def __init__(self):
# to have a tight packing on the chart wether only the x axis or also
# the y axis have (see matplotlib)
self.ytight = False
# y-margin (top/bottom) for the subcharts. This will not overrule the
# option plotinfo.plotymargin
self.yadjust = 0.0
# Each new line is in z-order below the previous one. change it False
# to have lines paint above the previous line
self.zdown = True
# Rotation of the date labes on the x axis
self.tickrotation = 15
# How many "subparts" takes a major chart (datas) in the overall chart
# This is proportional to the total number of subcharts
self.rowsmajor = 5
# How many "subparts" takes a minor chart (indicators/observers) in the
# overall chart. This is proportional to the total number of subcharts
# Together with rowsmajor, this defines a proportion ratio betwen data
# charts and indicators/observers charts
self.rowsminor = 1
# Distance in between subcharts
self.plotdist = 0.0
# Have a grid in the background of all charts
self.grid = True
# Default plotstyle for the OHLC bars which (line -> line on close)
# Other options: 'bar' and 'candle'
self.style = 'line'
# Default color for the 'line on close' plot
self.loc = 'black'
# Default color for a bullish bar/candle (0.75 -> intensity of gray)
self.barup = '0.75'
# Default color for a bearish bar/candle
self.bardown = 'red'
# Level of transparency to apply to bars/cancles (NOT USED)
self.bartrans = 1.0
# Wether the candlesticks have to be filled or be transparent
self.barupfill = True
self.bardownfill = True
# Wether the candlesticks have to be filled or be transparent
self.fillalpha = 0.20
# Wether to plot volume or not. Note: if the data in question has no
# volume values, volume plotting will be skipped even if this is True
self.volume = True
# Wether to overlay the volume on the data or use a separate subchart
self.voloverlay = True
# Scaling of the volume to the data when plotting as overlay
self.volscaling = 0.33
# Pushing overlay volume up for better visibiliy. Experimentation
# needed if the volume and data overlap too much
self.volpushup = 0.00
# Default colour for the volume of a bullish day
self.volup = '#aaaaaa' # 0.66 of gray
# Default colour for the volume of a bearish day
self.voldown = '#cc6073' # (204, 96, 115)
# Transparency to apply to the volume when overlaying
self.voltrans = 0.50
# Transparency for text labels (NOT USED CURRENTLY)
self.subtxttrans = 0.66
# Default font text size for labels on the chart
self.subtxtsize = 9
# Transparency for the legend (NOT USED CURRENTLY)
self.legendtrans = 0.25
# Wether indicators have a leged displaey in their charts
self.legendind = True
# Location of the legend for indicators (see matplotlib)
self.legendindloc = 'upper left'
# Plot the last value of a line after the Object name
self.linevalues = True
# Plot a tag at the end of each line with the last value
self.valuetags = True
# Default color for horizontal lines (see plotinfo.plothlines)
self.hlinescolor = '0.66' # shade of gray
# Default style for horizontal lines
self.hlinesstyle = '--'
# Default width for horizontal lines
self.hlineswidth = 1.0
# Default color scheme: Tableau 10
self.lcolors = tableau10
# strftime Format string for the display of ticks on the x axis
self.fmt_x_ticks = None
# strftime Format string for the display of data points values
self.fmt_x_data = None
PlotScheme クラスは、color(self, idx)
使用される色を返すメソッドを定義します。サブクラスはそれをオーバーロードでき、その idx パラメータは描画される線の現在のインデックスです。たとえば、MACD は 3 本の線を描画し、idx 変数には 0、1、2 の 3 つの値があります。新しいインジケーター idx は 0 から再開されます。デフォルトのカラースキームは でTableau 10 Color Palette
、対応するインデックスは ですtab10_index = [3, 0, 2, 1, 2, 4, 5, 6, 7, 8, 9]
。使用する色は、カスタム PlotScheme クラスの color() メソッドをオーバーライドするか、lcolors 変数をプロット メソッドに渡すことによって変更できます。
def color(self, idx):
colidx = tab10_index[idx % len(tab10_index)]
return self.lcolors[colidx]
ビジュアルコンポーネント
Backtrader は、次の 3 つの主要コンポーネントの視覚化をサポートしています。
-
データ フィード データ ソース: adddata、replaydata、および resampledata メソッドを通じてセレブロのオリジナル データをインポートします。
-
インジケーター: ストラテジー クラスで宣言されたインジケーター、または addindicator を通じて追加されたインジケーター
-
オブザーバー オブザーバー オブジェクト: addobserver を通じて追加されたオブザーバー (Cash オブジェクトや Value オブジェクトなど)
グラフィックを描画するとき、デフォルトではメイン チャートにデータ フィードが描画されます。移動平均などの一部の指標はデータ フィードとともにメイン チャートに描画され、一部はサブグラフの形式で描画されます。通常、オブザーバーは描画されます。サブピクチャにオン
視覚化オプション
前述した、plot() パラメーターとカスタム PlotScheme による視覚化オプションのシステム制御に加えて、インジケーターとオブザーバーには描画フォームを制御するためのオプションがいくつかあり、合計 3 つのタイプがあります。
-
オブジェクトのオブジェクト レベルの視覚化オプション - オブジェクト全体の描画動作に影響を与えることができ、plotinfo によって制御されます。
plotinfo = dict(plot=True, # 是否绘制
subplot=True, # 是否绘制成子图
plotname='', # 图形名称
plotabove=False, # 子图是否绘制在主图的上方
plotlinelabels=False, # 主图上曲线的名称
plotlinevalues=True,
plotvaluetags=True,
plotymargin=0.0,
plotyhlines=[],
plotyticks=[],
plothlines=[],
plotforce=False,
plotmaster=None,
plotylimited=True,
)
Lotinfo のプロパティにアクセスするには、次の 2 つの方法があります。
# 通过参数来设置
sma = bt.indicators.SimpleMovingAverage(self.data, period=15, plotname='mysma')
# 通过属性来设置
sma = bt.indicators.SimpleMovingAverage(self.data, period=15)
sma.plotinfo.plotname = 'mysma'
-
ライン関連の視覚化オプション - プロットライン オブジェクトを使用して、ライン オブジェクトの描画動作を制御できます。プロットラインのオプションは、以下に示すように、描画時に matplotlib に直接渡されます。
lines = ('histo',)
plotlines = dict(histo=dict(_method='bar', alpha=0.50, width=1.0))
-
メソッド制御の視覚化 — インジケーター インジケーターとオブザーバーを処理する場合、_plotlabel(self)、_plotinit(self) メソッドを使用すると、視覚化をさらに制御できます。
結論とコミュニケーション
詳細なコンテンツについては、WeChat 公開アカウント「Zhuge Shuo Talk」をフォローしてください。同時に、クオンツ投資グループへの招待を受け、多くの投資愛好家、クオンツ実践者、テクノロジー専門家とコミュニケーションやディスカッションをして、実戦での投資レベルを迅速に向上させることもできます。
記事を書くのは簡単ではありませんが、この記事が参考になったと思ったらクリックして読んでください。