为 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, 用于测试时取出。 

 

posted on   金凯旋  阅读(153)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2022-04-26 人总是善于忘记的
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示