为 vnpy 回测增加指标显示
添加一个指标类:
from vnpy.trader.ui import QtCore, QtGui
from vnpy.trader.object import BarData
from vnpy.chart.base import BLACK_COLOR, UP_COLOR, DOWN_COLOR, PEN_WIDTH, BAR_WIDTH,WHITE_COLOR
from vnpy.chart.item import CandleItem
from vnpy.trader.object import BarData
from vnpy.chart.manager import BarManager
class LineItem(CandleItem):
""" LineItem 用于策略内线性标线图示 """
prompt = "Line"
def __init__(self, manager: BarManager) -> None:
""""""
super().__init__(manager)
self.lineList = []
self._color = WHITE_COLOR
def setData(self, lineList : list, prompt:str, color : QtGui.QColor = WHITE_COLOR):
self.lineList = lineList
self._color = color
self.prompt = prompt
def _draw_bar_picture(self, ix: int, _) -> QtGui.QPicture:
""""""
candle_picture: QtGui.QPicture = QtGui.QPicture()
painter: QtGui.QPainter = QtGui.QPainter(candle_picture)
painter.setPen(QtGui.QPen(self._color))
if ix != 0:
if self.lineList[ix - 1] != None and self.lineList[ix] != None:
painter.drawLine(
QtCore.QPointF(ix - 1, self.lineList[ix - 1]),
QtCore.QPointF(ix, self.lineList[ix])
)
painter.end()
return candle_picture
def get_info_text(self, ix: int) -> str:
""""""
if ix < len(self.lineList) and self.lineList[ix]:
text = f"{self.prompt}:{self.lineList[ix]:.2f}"
else:
text = f"{self.prompt}:None"
return text
class TextItem(CandleItem):
""" TextItem 在左边窗口显示文字 """
def __init__(self, manager: BarManager) -> None:
super().__init__(manager)
self.lineList : list = []
def setData(self, lineList : list, prompt:str) -> None:
self.lineList = lineList
self.prompt = prompt
def get_info_text(self, ix: int) -> str:
if ix >= 0 and ix < len(self.lineList) and self.lineList[ix]:
text = f"{self.prompt}:{self.lineList[ix]}"
else:
text = "---"
return text
调用指标的代码:
engine : BacktestingEngine = backtest(BreakStrategy)
while create_qapp():
# 建立K线图表
candle_dialog: CandleChartDialog = CandleChartDialog()
# 增加指标
candle_dialog.chart.add_item(LineItem, "mean", "candle")
candle_dialog.chart.add_item(LineItem, "up", "candle")
candle_dialog.chart.add_item(LineItem, "down", "candle")
# 设置指标数值
candle_dialog.chart._items["mean"].setData(engine.strategy.mean_list, "mean", QtGui.QColor(255, 0, 0))
candle_dialog.chart._items["up"].setData(engine.strategy.bollup_list, "up", QtGui.QColor(155, 155, 155))
candle_dialog.chart._items["down"].setData(engine.strategy.bolldown_list, "down", QtGui.QColor(155, 155, 155))
# 设置K线图表的数据
history: list = engine.history_data
# 更新K线图表的数据
candle_dialog.update_history(history)
# 更新K线图表的成交记录
trades: List[TradeData] = engine.get_all_trades()
candle_dialog.update_trades(trades)
candle_dialog.exec()
break
print("task finished")
要点:
在update_history 前 additem 和 setData, 因为 CandleChartDialog 里的 update_history 里直接更新了画图内容。
策略代码里,要生成指标list, 用于测试时取出。