1. 概述
NewChartWidget 是一个基于 PyQtGraph 的金融K线图组件,专为量化交易设计。它提供了灵活的可视化功能,包括蜡烛图、成交量、MA指标和MACD指标等。该组件通过模块化的设计,允许用户轻松添加和配置不同的图表元素。
2. 核心功能实现
2.1 多图层管理
NewChartWidget 支持多个独立的绘图区域,每个区域可以显示不同的指标数据。通过 add_plot() 方法创建新的绘图区域:
def add_plot(
self,
plot_name: str,
minimum_height: int = 80,
maximum_height: int = None,
hide_x_axis: bool = False
) -> None:
# 创建PlotItem对象
plot: pg.PlotItem = pg.PlotItem(axisItems={'bottom': self._get_new_x_axis()})
plot.setMenuEnabled(False)
plot.setClipToView(True)
plot.hideAxis('left')
plot.showAxis('right')
plot.setDownsampling(mode='peak')
plot.setRange(xRange=(0, 1), yRange=(0, 1))
plot.hideButtons()
plot.setMinimumHeight(minimum_height)
2.2 数据更新机制
组件提供了两种数据更新方式:批量更新和实时更新。update_history() 用于初始化或批量更新历史数据,update_bar() 用于实时更新最新数据:
def update_history(self, history: List[BarData]) -> None:
self._manager.update_history(history)
for item in self._items.values():
item.update_history(history)
self._update_plot_limits()
self.move_to_right()
def update_bar(self, bar: BarData) -> None:
self._manager.update_bar(bar)
for item in self._items.values():
item.update_bar(bar)
self._update_plot_limits()
if self._right_ix >= (self._manager.get_count() - self._bar_count / 2):
self.move_to_right()
2.3 交互功能
NewChartWidget 提供了丰富的交互功能,包括十字光标、价格标签、键盘导航和鼠标缩放等。通过 add_cursor() 方法添加十字光标:
def add_cursor(self) -> None:
if not self._cursor:
self._cursor = ChartCursor(
self, self._manager, self._plots, self._item_plot_map)
2.4 性能优化
组件通过以下方式优化性能:
- 动态计算和更新每个plot的y轴范围
- 只更新当前可见区域的数据
- 使用pyqtgraph的downsampling功能优化大数据量显示
def _update_plot_limits(self) -> None:
for item, plot in self._item_plot_map.items():
min_value, max_value = item.get_y_range()
plot.setLimits(
xMin=-1,
xMax=self._manager.get_count(),
yMin=min_value,
yMax=max_value
)
3. 使用示例
以下代码展示了如何使用NewChartWidget来展示BTC-USDT的K线数据:
if __name__ == "__main__":
app = create_qapp()
# 创建图表组件
widget = NewChartWidget()
# 添加绘图区域
widget.add_plot("candle", hide_x_axis=True)
widget.add_plot("volume", maximum_height=100)
widget.add_plot("macd", maximum_height=100)
# 添加图表元素
widget.add_item(CandleItem, "candle", "candle")
widget.add_item(VolumeItem, "volume", "volume")
widget.add_item(MaItem, "ma", "candle")
widget.add_item(MacdItem, "macd", "macd")
# 添加交互元素
widget.add_last_price_line()
widget.add_cursor()
4. 运行结果
运行上述代码后,将会显示一个包含以下内容的K线图窗口:
4.1 主图区域:
- 显示BTC-USDT的分钟级K线图
- 包含蜡烛图和MA移动平均线
4.2 成交量区域:
- 显示对应时间段的成交量柱状图
4.3 MACD区域:
- 显示MACD指标及其信号线
4.4 交互功能:
- 鼠标悬停时显示十字光标和价格信息
- 支持鼠标滚轮缩放和拖动查看历史数据
5. 扩展与定制
开发者可以根据需要扩展NewChartWidget的功能:
- 添加新的技术指标
- 自定义颜色主题
- 实现更复杂的交互逻辑
- 集成实时数据源
通过这种模块化的设计,NewChartWidget可以灵活地适应各种金融数据可视化需求,为量化交易提供了可靠的可视化支持。
6. 联系方式
- 公众号:ScienceStudio
- Github: github.com/KandyYe
- 知乎:www.zhihu.com/people/Scie…