PyQt5系列教程(90):一美元值多少錢?-3
今天我們把剩下兩個類介紹下。
DrawChart
class DrawChart():
def __init__(self):
self.data_list, self.t = self.getData()
def pyqtgraphDrawChart(self):
try:
self.item = CandlestickItem(self.data_list)
self.xdict = {0: self.data_list[0][1], int((self.t + 1) / 2) - 1: self.data_list[int((self.t + 1) / 2) - 1][1], self.t - 1: self.data_list[-1][1]}
self.stringaxis = pg.AxisItem(orientation=bottom)
self.stringaxis.setTicks([self.xdict.items()])
self.plt = pg.PlotWidget(axisItems={bottom: self.stringaxis}, enableMenu=False)
self.plt.addItem(self.item)
return self.plt
except:
return pg.PlotWidget()
def getData(self):
self.exr_data = pandas.read_csv("rmb.csv").sort_index(ascending=False)
data_list = []
t = 0
for index, row in self.exr_data.iterrows():
date, close, open, high, low, price_change = row
datas = (t, date, close, open, high, low, price_change)
data_list.append(datas)
t = t + 1
return data_list, t
這裡先把數據來源問題介紹下。
程序中的美元兌換人民幣的匯率數據我是從網站上下的,格式是csv,如下圖:
至於哪個網站大家自己找吧(這裡避嫌),網上很多。外匯交易國內是沒有開放的,凡是自己聲稱正規合法的,都是騙子。

當然還有一種是國外是有資質受到監管的交易平台,在國內發展業務,這種能否可行就需要自己甄別了。
def getData(self):
self.exr_data = pandas.read_csv("rmb.csv").sort_index(ascending=False)
data_list = []
t = 0
for index, row in self.exr_data.iterrows():
date, close, open, high, low, price_change = row
datas = (t, date, close, open, high, low, price_change)
data_list.append(datas)
t = t + 1
return data_list, t
我們使用pandas讀取csv文件(倒序),這樣日期就是從2018年1月1日開始了。
然後我們把相關的信息連同序號t一起放入datas元組中,再把這個元組放入data_list這個列表中。結果返回。
def pyqtgraphDrawChart(self):
try:
self.item = CandlestickItem(self.data_list)
self.xdict = {0: self.data_list[0][1], int((self.t + 1) / 2) - 1: self.data_list[int((self.t + 1) / 2) - 1][1], self.t - 1: self.data_list[-1][1]}
self.stringaxis = pg.AxisItem(orientation=bottom)
self.stringaxis.setTicks([self.xdict.items()])
self.plt = pg.PlotWidget(axisItems={bottom: self.stringaxis}, enableMenu=False)
self.plt.addItem(self.item)
return self.plt
except:
return pg.PlotWidget()
這裡使用try…except…的方式,避免pyqtgraph發生一些未知錯誤。
CandlestickItem是我們的K線圖,self.xdict則是我們下面的坐標,如下圖:
self.stringaxis = pg.AxisItem(orientation=bottom)
self.stringaxis.setTicks([self.xdict.items()])
pg.AxisItem顯示帶有刻度,值和標籤的單個繪圖軸。 可以配置為適合繪圖的任何一側,這裡我們是在下面。
setTicks()明確確定要顯示的刻度,如下圖:

self.plt是我們創建的顯示K線圖的和坐標刻度的小部件。後面會和PyQt5整合在一起。
ExchangeRate
class ExchangeRate(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(ExchangeRate, self).__init__(parent)
self.setupUi(self)
self.InitUi()
def InitUi(self):
self.splitter.setStretchFactor(0, 4)
self.splitter.setStretchFactor(1, 6)
pg.setConfigOption(background, #f0f0f0)
self.drawChart = DrawChart()
self.exrwidget = self.drawChart.pyqtgraphDrawChart()
self.verticalLayout.addWidget(self.exrwidget)
self.vLine = pg.InfiniteLine(angle=90, movable=False)
self.hLine = pg.InfiniteLine(angle=0, movable=False)
self.exrwidget.addItem(self.vLine, ignoreBounds=True)
self.exrwidget.addItem(self.hLine, ignoreBounds=True)
self.exrwidget.scene().sigMouseMoved.connect(self.mouseMoved)
def mouseMoved(self, pos):
vb = self.exrwidget.plotItem.vb
if self.exrwidget.sceneBoundingRect().contains(pos):
mousePoint = vb.mapSceneToView(pos)
index = int(mousePoint.x()+1/3.)
if index >= 0 and index < len(self.drawChart.data_list):
date, close, open, high, low, price_change = self.drawChart.data_list[index][1::]
self.label_date_c.setText(date)
self.label_close_c.setText(str(close))
self.label_open_c.setText(str(open))
self.label_high_c.setText(str(high))
self.label_low_c.setText(str(low))
self.label_change_c.setText(price_change)
if price_change[0] == "-":
self.label_change_c.setStyleSheet("color:green")
elif price_change == "0.00%":
self.label_change_c.setStyleSheet("color:black")
else:
self.label_change_c.setStyleSheet("color:red")
self.vLine.setPos(mousePoint.x())
self.hLine.setPos(mousePoint.y())
這個類我們用來處理與PyQt5的整合還有滑鼠移動事件。
pg.setConfigOption(background, #f0f0f0)
設置背景色,沒有這句效果是這樣的:

貌似挺丑的。
self.drawChart = DrawChart()
self.exrwidget = self.drawChart.pyqtgraphDrawChart()
self.verticalLayout.addWidget(self.exrwidget)
我們將生成的pyqtgraph小部件放入到PyQt5的布局中。
self.vLine = pg.InfiniteLine(angle=90, movable=False)
self.hLine = pg.InfiniteLine(angle=0, movable=False)
self.exrwidget.addItem(self.vLine, ignoreBounds=True)
self.exrwidget.addItem(self.hLine, ignoreBounds=True)
增加x軸、y軸方向上的線,如下圖:

self.exrwidget.scene().sigMouseMoved.connect(self.mouseMoved)
處理滑鼠移動時,線也要跟著移動,此時的信號是sigMouseMoved。
vb = self.exrwidget.plotItem.vb
vb這裡指的是ViewBox,允許通過滑鼠拖動對其進行內部縮放/平移的框。此類通常作為PlotItem或Canvas的一部分或使用GraphicsLayout.addViewBox()自動創建。
特徵:
- 內容更改時,通過滑鼠縮放內容或自動縮放
- 查看鏈接多個視圖顯示相同的數據範圍
- 可通過上下文菜單配置
- 項目坐標映射方法
mousePoint = vb.mapSceneToView(pos)
index = int(mousePoint.x()+1/3.)
if index >= 0 and index < len(self.drawChart.data_list):
date, close, open, high, low, price_change = self.drawChart.data_list[index][1::]
self.label_date_c.setText(date)
self.label_close_c.setText(str(close))
self.label_open_c.setText(str(open))
self.label_high_c.setText(str(high))
self.label_low_c.setText(str(low))
self.label_change_c.setText(price_change)
if price_change[0] == "-":
self.label_change_c.setStyleSheet("color:green")
elif price_change == "0.00%":
self.label_change_c.setStyleSheet("color:black")
else:
self.label_change_c.setStyleSheet("color:red")
如果你的滑鼠坐標在範圍內,我們要把這個坐標轉換成每一天的行情index。
index的範圍在0到全部的匯率數據行上。
然後我們把匯率數據轉換到qlabel,即顯示出這一天匯率行情的全部信息。
對匯率變化的label對象,我們根據具體的變化多少設置樣式,正值紅色,負值綠色,其它為黑色,如下圖:
最 後
今天的內容就到這兒,我們下期再會!如果你喜歡本篇文章,請給我點贊
讚賞(推薦)
分享給你的好友們吧!
歡迎關注微信公眾號:學點編程吧,發送:pyqt590,可以獲得本期代碼。加油!
(? ??_??)? (*????)
推薦閱讀:
