在backtrader中,版本号为1.9.78.123;在回测历史K线图… · The Chat Archive
Explore / History & society 在backtrader中,版本号为1.9.78.123;在回测历史K线图时,某K线满足条件1,再经过几根K线后,再满足条件2;如此循环,共有N组这样一一对应的K线,如何在每组K线… Save Share Download ▾ Report在backtrader中,版本号为1.9.78.123;在回测历史K线图时,某K线满足条件1,再经过几根K线后,再满足条件2;如此循环,共有N组这样一一对应的K线,如何在每组K线的收盘价间画一条直线?且要求只能显示在主图中
Assistant2023-05-24 08:51 UTC Copy response
可以使用ztelen/lines指标来在主图中画出直线。具体步骤如下:
创建一个Lines指标的子类,例如命名为 ,重载 方法,用一个列表保存所有符合条件的K线的收盘价坐标,用一个标志变量保存是否达到满足条件2的状态。
Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language zh
Conversation date May 24, 2023
Added to archive Nov 16, 2026
ID 01m7h41abmyehf5527dc3an5q9Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: cd711d4430ca266e122eba603cf13052
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
MyLine
__init__
from backtrader.indicators import Indicator, PlotLines
import numpy as np
class MyLine(Indicator):
lines = ('line',)
plotinfo = dict(plot=False, subplot=True)
plotlines = dict(line=dict(_plotskip=True))
def __init__(self, close, condition1, condition2):
self.addminperiod(close, 0)
self.close = close
self.condition1 = condition1
self.condition2 = condition2
self.line_coords = []
self.reached_condition2 = False
在next方法中判断是否满足条件1或条件2,并更新line_coords和reached_condition2的值。
def next(self):
if not self.reached_condition2:
if self.condition1:
self.line_coords.append((self.data.datetime.datetime(), self.close[0]))
elif self.condition2:
self.line_coords.append((self.data.datetime.datetime(), self.close[0]))
self.reached_condition2 = True
else:
if self.condition1:
self.line_coords.append((self.data.datetime.datetime(), self.close[0]))
self.reached_condition2 = False
self.lines.line.set_lines(np.array(self.line_coords))
self.line_coords = []
else:
self.line_coords.append((self.data.datetime.datetime(), self.close[0]))
将MyLine指标添加到策略实例中。例如,假设condition1和condition2分别是两个自定义函数,判断是否满足条件1和条件2,可以在__init__方法中添加如下代码:
class MyStrategy(bt.Strategy):
def __init__(self):
...
myline = MyLine(self.data.close, condition1, condition2)
self.add_indicator(myline)
...
在plot方法中将MyLine指标添加到主图中,并设置线条颜色和风格。
def plot(self, plotmaster=True, **kwargs):
...
for i, d in enumerate(self.datas):
...
# Add MyLine indicator to plot
for indic in d.indicators:
if isinstance(indic, MyLine):
lp = bt.plotting.PlotLines(
self.data.lines.datetime.get(index=True),
indic.line_coords,
_name='MyLine',
width=2,
color='black',
style='solid',
subplot=False)
self.plotinfo.plotlines.append(lp)
...
这样就可以在回测历史K线图中,每组符合条件1和条件2的K线的收盘价之间画出直线。
Not yet included in a published release.