python_PyQt5日周月K线纵向对齐显示_2_显示工具

2023-10-31 02:20

本文主要是介绍python_PyQt5日周月K线纵向对齐显示_2_显示工具,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

写在前面:

结果显示:

代码:

计算日数据、周数据,月数据,并返回

生成提示信息数据,同时将日周月合并到一个DataFrame中

返回K线图和成交量柱状图的数据

主界面,显示日周月对齐的K线图

使用方法


写在前面:

“PyQt5日周月K线纵向对齐显示”,将分三篇博文描述

1 数据处理。将数据处理成适合图形显示的格式。(已写,请看往期博文)

2 显示工具开发。用pyqtgraph开发

3 聚焦某段图形

结果显示:

日周月,K线图与成交量柱状图,共6个图拼接在一起,滚动显示,横坐标对齐

代码:

在前面博文中有介绍了主要数据处理的逻辑,这里直接上代码。

计算日数据、周数据,月数据,并返回

def temp_000():junxian = 20columns_list = ['row_i', 'tradeDate', 'openPrice', 'highestPrice', 'lowestPrice', 'closePrice','turnoverVol', 'turnoverValue','ma','vol_ma','value_ma']file_path = r'E:/temp003/600941.xlsx'df = pd.read_excel(file_path,engine='openpyxl')df['row_i'] = [i for i in range(len(df))]df['o_date'] = pd.to_datetime(df['tradeDate'])df['ma'] = talib.MA(df['closePrice'], timeperiod=junxian)df['vol_ma'] = talib.MA(df['turnoverVol'], timeperiod=junxian)df['value_ma'] = talib.MA(df['turnoverValue'], timeperiod=junxian)week_group = df.resample('W-FRI', on='o_date')month_group = df.resample('M', on='o_date')week_df = week_group.last()week_df['row_i'] = week_group.last()['row_i']week_df['openPrice'] = week_group.first()['openPrice']week_df['lowestPrice'] = week_group.min()['lowestPrice']week_df['highestPrice'] = week_group.max()['highestPrice']week_df['turnoverVol'] = week_group.sum()['turnoverVol']week_df['turnoverValue'] = week_group.sum()['turnoverValue']week_df = week_df.loc[:, columns_list].copy()week_df.dropna(axis=0, how='any', subset=['closePrice'], inplace=True)week_df['ma'] = talib.MA(week_df['closePrice'], timeperiod=junxian)week_df['vol_ma'] = talib.MA(week_df['turnoverVol'], timeperiod=junxian)week_df['value_ma'] = talib.MA(week_df['turnoverValue'], timeperiod=junxian)month_df = month_group.last()month_df['row_i'] = month_group.last()['row_i']month_df['openPrice'] = month_group.first()['openPrice']month_df['lowestPrice'] = month_group.min()['lowestPrice']month_df['highestPrice'] = month_group.max()['highestPrice']month_df['turnoverVol'] = month_group.sum()['turnoverVol']month_df['turnoverValue'] = month_group.sum()['turnoverValue']month_df = month_df.loc[:, columns_list].copy()month_df.dropna(axis=0, how='any', subset=['closePrice'], inplace=True)month_df['ma'] = talib.MA(month_df['closePrice'], timeperiod=junxian)month_df['vol_ma'] = talib.MA(month_df['turnoverVol'], timeperiod=junxian)month_df['value_ma'] = talib.MA(month_df['turnoverValue'], timeperiod=junxian)daily_df = df.loc[:, columns_list].copy()return daily_df, week_df, month_df# daily_df.to_excel(r'E:/temp009/day.xlsx',engine='openpyxl')# week_df.to_excel(r'E:/temp009/week.xlsx',engine='openpyxl')# month_df.to_excel(r'E:/temp009/month.xlsx',engine='openpyxl')return daily_df,week_df,month_df

生成提示信息数据,同时将日周月合并到一个DataFrame中

def temp_001(daily_df,week_df,month_df):week_df.rename(columns={'row_i': 'week_i', 'tradeDate': 'week_tradeDate', 'closePrice': 'week_close', 'openPrice': 'week_open','lowestPrice': 'week_low', 'highestPrice': 'week_high', 'turnoverVol': 'week_turnoverVol','turnoverValue': 'week_turnoverValue'}, inplace=True)month_df.rename(columns={'row_i': 'month_i', 'tradeDate': 'month_tradeDate', 'closePrice': 'month_close','openPrice': 'month_open', 'lowestPrice': 'month_low', 'highestPrice': 'month_high','turnoverVol': 'month_turnoverVol', 'turnoverValue': 'month_turnoverValue'}, inplace=True)three_df = pd.merge(daily_df, week_df, how='left', left_on='tradeDate', right_on='week_tradeDate')three_df.fillna(method='bfill', inplace=True)three_df = pd.merge(three_df, month_df, how='left', left_on='tradeDate', right_on='month_tradeDate')three_df.fillna(method='bfill', inplace=True)# three_df.to_excel(r'E:/temp009/111/three.xlsx',engine='openpyxl')res_map = {}for i, row in three_df.iterrows():row_i = row['row_i']res_map[str(row_i)] = {'日期': row['tradeDate'],'收盘价': row['closePrice'],'开盘价': row['openPrice'],'最高价': row['highestPrice'],'最低价': row['lowestPrice'],'成交量': row['turnoverVol'],'成交额': row['turnoverValue'],'周': row['week_tradeDate'],'周收盘价': row['week_close'],'周开盘价': row['week_open'],'周最高价': row['week_high'],'周最低价': row['week_low'],'周成交量': row['week_turnoverVol'],'周成交额': row['week_turnoverValue'],'月': row['month_tradeDate'],'月收盘价': row['month_close'],'月开盘价': row['month_open'],'月最高价': row['month_high'],'月最低价': row['month_low'],'月成交量': row['month_turnoverVol'],'月成交额': row['month_turnoverValue']}return res_map, three_df

返回K线图和成交量柱状图的数据

def temp_002(df):# 生成K线图和成交量柱状图k_height_num = 400vol_height_num = 100candle_data = df.loc[:, ['row_i', 'openPrice', 'closePrice', 'lowestPrice', 'highestPrice']].values.tolist()curve_data = {'x': df['row_i'].values.tolist(),'y': df['ma'].values.tolist()}one = {'height_num': k_height_num,'yMin': df['lowestPrice'].min(),'yMax': df['highestPrice'].max(),'data_list': [{'type': 'candle','data': candle_data},{'type': 'curve','data': curve_data}]}bar_data = df.loc[:, ['row_i', 'openPrice', 'closePrice', 'turnoverVol']].values.tolist()curve_data2 = {'x': df['row_i'].values.tolist(),'y': df['vol_ma'].values.tolist()}two = {'height_num': vol_height_num,'yMin': 0,'yMax': df['turnoverVol'].max(),'data_list': [{'type': 'bar','data': bar_data},{'type': 'curve','data': curve_data2}]}return one, two

K线控件、成交量bar控件

class CandlestickItem(pg.GraphicsObject):def __init__(self, data):pg.GraphicsObject.__init__(self)self.data = data  ## data must have fields: time, open, close, min, maxself.generatePicture()def generatePicture(self):## pre-computing a QPicture object allows paint() to run much more quickly,## rather than re-drawing the shapes every time.self.picture = QtGui.QPicture()p = QtGui.QPainter(self.picture)p.setPen(pg.mkPen('d'))# w = (self.data[1][0] - self.data[0][0]) / 3.w = 0.3for (t, open, close, min, max) in self.data:p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))if open < close:p.setBrush(pg.mkBrush('r'))else:p.setBrush(pg.mkBrush('g'))p.drawRect(QtCore.QRectF(t-w, open, w * 2, close - open))p.end()def paint(self, p, *args):p.drawPicture(0, 0, self.picture)def boundingRect(self):## boundingRect _must_ indicate the entire area that will be drawn on## or else we will get artifacts and possibly crashing.## (in this case, QPicture does all the work of computing the bouning rect for us)return QtCore.QRectF(self.picture.boundingRect())class VOLtickItem(pg.GraphicsObject):def __init__(self, data):pg.GraphicsObject.__init__(self)self.data = data  ## data must have fields: time,open,close, volself.generatePicture()def generatePicture(self):self.picture = QtGui.QPicture()p = QtGui.QPainter(self.picture)p.setPen(pg.mkPen('d'))# w = (self.data[1][0] - self.data[0][0]) / 3.w = 0.3for (t,open,close, vol) in self.data:if open < close:p.setBrush(pg.mkBrush('r'))else:p.setBrush(pg.mkBrush('g'))p.drawRect(QtCore.QRectF(t - w, 0, w * 2, vol))p.end()def paint(self, p, *args):p.drawPicture(0, 0, self.picture)def boundingRect(self):## boundingRect _must_ indicate the entire area that will be drawn on## or else we will get artifacts and possibly crashing.## (in this case, QPicture does all the work of computing the bouning rect for us)return QtCore.QRectF(self.picture.boundingRect())

主界面,显示日周月对齐的K线图

class ExampleWidget(QtWidgets.QWidget):def __init__(self):super().__init__()self.init_data()self.init_ui()passdef init_data(self):self.v_list = []self.vline_list = []self.hline_list = []self.label_list = []self.data_list = []self.show_map: Dict = {}self.mark_data_map: Dict = {}self.mark_item_map: Dict = {}self.graph_type_candle: str = 'candle'self.graph_type_curve: str = 'curve'self.graph_type_bar: str = 'bar'self.tip_show_yeah: bool = Falsepassdef init_ui(self):self.setMinimumWidth(800)self.setMinimumHeight(600)origin_btn = QtWidgets.QPushButton('返回原位')origin_btn.clicked.connect(self.origin_btn_clicked)self.tip_checkbox = QtWidgets.QCheckBox('数据提示框')self.tip_checkbox.stateChanged.connect(self.tip_checkbox_stateChanged)layout1 = QtWidgets.QHBoxLayout()layout1.addWidget(origin_btn)layout1.addWidget(self.tip_checkbox)layout1.addStretch(1)self.pw_layout = QtWidgets.QVBoxLayout()self.scroll_area = QtWidgets.QScrollArea()self.scroll_area.setWidgetResizable(True)self.scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)self.scroll_area.setViewportMargins(20,20,20,20)layout = QtWidgets.QVBoxLayout()layout.addLayout(layout1)layout.addWidget(self.scroll_area)self.setLayout(layout)passdef focus_location(self,left_x:int,right_x:int,y_data:List):if self.v_list:v0 = self.v_list[0]v0.setXRange(min=left_x,max=right_x)for i,v in enumerate(self.v_list):y_node = y_data[i]v.setYRange(min=y_node[0],max=y_node[1])passdef restart_init(self):self.v_list.clear()self.vline_list.clear()self.hline_list.clear()self.label_list.clear()self.data_list.clear()self.show_map.clear()passdef origin_btn_clicked(self):if self.v_list:v0 = self.v_list[0]v0.enableAutoRange() # 还原到初始状态passdef tip_checkbox_stateChanged(self):if self.tip_checkbox.isChecked():self.tip_show_yeah = Trueelse:self.tip_show_yeah = Falsepassdef set_data(self,data:Dict):self.restart_init()self.show_map = data['show_map']self.data_list = data['data_list']self.fill_viewbox()passdef fill_viewbox(self):pw = pg.GraphicsLayoutWidget(show=False)h_i = 0for i,node in enumerate(self.data_list):'''height_numdata_list:[{type:candle,curve,bardata:[]},{}]'''v = pw.addViewBox(row=i, col=0)v.setMouseEnabled(x=True, y=False)v.setAutoVisible(x=False, y=True)height_num = node['height_num']node_yMin = node['yMin']node_yMax = node['yMax']pw.ci.layout.setRowMinimumHeight(i, height_num)v.setLimits(yMin=node_yMin, yMax=node_yMax)h_i += height_numif i>0:v.setXLink(self.v_list[0])node_data_list = node['data_list']for one in node_data_list:one_type = one['type']one_data = one['data']if one_type == self.graph_type_candle:candle = CandlestickItem(one_data)v.addItem(candle)elif one_type == self.graph_type_curve:curve = pg.PlotCurveItem(x=one_data['x'],y=one_data['y'],pen=(0,0,255))v.addItem(curve)passelif one_type == self.graph_type_bar:bar = VOLtickItem(one_data)v.addItem(bar)passelse:passpassvLine = pg.InfiniteLine(angle=90, movable=False)hLine = pg.InfiniteLine(angle=0, movable=False)label = pg.TextItem()v.addItem(vLine, ignoreBounds=True)v.addItem(hLine, ignoreBounds=True)v.addItem(label, ignoreBounds=True)v.scene().sigMouseMoved.connect(self.mouseMoved)self.v_list.append(v)self.vline_list.append(vLine)self.hline_list.append(hLine)self.label_list.append(label)passpw.setFixedHeight(h_i+50)self.fill_pw_widget(pw)passdef fill_pw_widget(self,pw):# print(pw.width(),pw.height())# 清空控件while self.pw_layout.count():item = self.pw_layout.takeAt(0)widget = item.widget()if widget is not None:widget.deleteLater()passsc_child_widget = self.scroll_area.takeWidget()if sc_child_widget is not None:sc_child_widget.deleteLater()# for item in self.pw_widgets_list:#     self.pw_layout.addWidget(item)self.pw_layout.addWidget(pw)one_sc_child_widget = QtWidgets.QWidget()one_sc_child_widget.setLayout(self.pw_layout)self.scroll_area.setWidget(one_sc_child_widget)passdef mouseMoved(self,evt):pos = evtfor la in self.label_list:la.setHtml("")la.setPos(-1, -1)for i,v in enumerate(self.v_list):if v.sceneBoundingRect().contains(pos):mousePoint = v.mapSceneToView(pos)index = int(mousePoint.x())hline = self.hline_list[i]hline.setPos(mousePoint.y())for hi,hl in enumerate(self.hline_list):if hi!=i:hl.setPos(-1)passfor vl in self.vline_list:vl.setPos(mousePoint.x())if self.tip_show_yeah and self.show_map.get(str(index)):node_one = self.show_map[str(index)]node_str = "<span style='font-size:12pt;color:red'>"n_i = 1for k,v in node_one.items():if n_i%7 == 0:node_str += f"{k}:{v}<br/>"else:node_str += f"{k}:{v}&nbsp;"n_i += 1passnode_str += "</span>"tip_label = self.label_list[i]tip_label.setHtml(node_str)tip_label.setPos(mousePoint.x(),mousePoint.y())passelse:for la in self.label_list:la.setHtml("")la.setPos(-1,-1)passbreakpasspasspass

使用方法

if __name__ == '__main__':QtCore.QCoreApplication.setAttribute(QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)app = QtWidgets.QApplication(sys.argv)main_window = ExampleWidget()# main_window.show()# app.exec()day_df,week_df,month_df = temp_000()k_tip_map, three_df = temp_001(day_df.copy(),week_df.copy(),month_df.copy())one,two = temp_002(day_df.copy())three,four = temp_002(week_df.copy())five,six = temp_002(month_df.copy())base_k_data = {'show_map': k_tip_map,'data_list': [one, two, three, four, five, six]}main_window.set_data(base_k_data)main_window.show()app.exec()pass

这篇关于python_PyQt5日周月K线纵向对齐显示_2_显示工具的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/312129

相关文章

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库

Python Web框架Flask、Streamlit、FastAPI示例详解

《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre

Python实现PDF按页分割的技术指南

《Python实现PDF按页分割的技术指南》PDF文件处理是日常工作中的常见需求,特别是当我们需要将大型PDF文档拆分为多个部分时,下面我们就来看看如何使用Python创建一个灵活的PDF分割工具吧... 目录需求分析技术方案工具选择安装依赖完整代码实现使用说明基本用法示例命令输出示例技术亮点实际应用场景扩

Python错误AttributeError: 'NoneType' object has no attribute问题的彻底解决方法

《Python错误AttributeError:NoneTypeobjecthasnoattribute问题的彻底解决方法》在Python项目开发和调试过程中,经常会碰到这样一个异常信息... 目录问题背景与概述错误解读:AttributeError: 'NoneType' object has no at

Python使用openpyxl读取Excel的操作详解

《Python使用openpyxl读取Excel的操作详解》本文介绍了使用Python的openpyxl库进行Excel文件的创建、读写、数据操作、工作簿与工作表管理,包括创建工作簿、加载工作簿、操作... 目录1 概述1.1 图示1.2 安装第三方库2 工作簿 workbook2.1 创建:Workboo

基于Python实现简易视频剪辑工具

《基于Python实现简易视频剪辑工具》这篇文章主要为大家详细介绍了如何用Python打造一个功能完备的简易视频剪辑工具,包括视频文件导入与格式转换,基础剪辑操作,音频处理等功能,感兴趣的小伙伴可以了... 目录一、技术选型与环境搭建二、核心功能模块实现1. 视频基础操作2. 音频处理3. 特效与转场三、高

Python实现中文文本处理与分析程序的示例详解

《Python实现中文文本处理与分析程序的示例详解》在当今信息爆炸的时代,文本数据的处理与分析成为了数据科学领域的重要课题,本文将使用Python开发一款基于Python的中文文本处理与分析程序,希望... 目录一、程序概述二、主要功能解析2.1 文件操作2.2 基础分析2.3 高级分析2.4 可视化2.5

一文解密Python进行监控进程的黑科技

《一文解密Python进行监控进程的黑科技》在计算机系统管理和应用性能优化中,监控进程的CPU、内存和IO使用率是非常重要的任务,下面我们就来讲讲如何Python写一个简单使用的监控进程的工具吧... 目录准备工作监控CPU使用率监控内存使用率监控IO使用率小工具代码整合在计算机系统管理和应用性能优化中,监

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho