天天996的生活让人喘不上气来,最近连肉都快买不起了。还不赶紧发挥下自己的特长,增加些被动收入,早日走上财务自由之路?用Python你可以做到这一点。今天我们先实现看盘,虽然有众多看盘软件可以使用,但花花绿绿的界面看着就头大,我们只需要一个当前股价就好了。
easyquotation是国人出的一款Python库,可以抓取国内股票信息。先创建个数组存放股票代码,qq是指腾迅网站的行情。
stocks = ['sz002415', 'sz002237', 'sz002600', 'sz002230', 'sz000333', 'sz000651', 'sz000725', 'sz200725',
'sz601989', 'sz000951', 'sz002024', 'sz600004']
quotation = easyquotation.use('qq')
price = quotation.stocks(stocks, prefix=True)
print(price)
虽然指标很多,但我们只关心当前股价, 开盘价,收盘价等,我们当然可以用一个循环再在json里取属性, 但用高级一点的库比如Pandas, 直接就可以过滤出我们感兴趣的列。
hk = pd.DataFrame(price)
hk = hk.T.ix[:, ['name', 'now', 'open', 'close']]
price = hk.iterrows()
因为股票价格时刻在变,就需要在后台每隔5秒取一下数据,然后更新界面。用Qt自带的QThread是很容易的,象常见的多线程框架一样,我们在run方法里取股价,然后发射相应的股价,用简单的冒号分割。然后在UI主线程里拿到信号,刷新对应的表格值即可。不然的话,很容易在取股价的时候锁死界面。
完整的代码如下
import sys
import easyquotation
import pandas as pd
from PyQt5.QtCore import QTimer, pyqtSignal, QThread
from PyQt5.QtWidgets import *
stocks = ['sz002415', 'sz002237', 'sz002600', 'sz002230', 'sz000333', 'sz000651', 'sz000725', 'sz200725',
'sz601989', 'sz000951', 'sz002024', 'sz600004']
class Stock():
name = ""
now = ""
close = ""
open = ""
def __init__(self, stockId):
self.stockId = stockId
class WorkThread(QThread):
trigger = pyqtSignal(str)
def __int__(self):
super(WorkThread, self).__init__()
def run(self):
global stocks
try:
quotation = easyquotation.use('qq')
price = quotation.stocks(stocks, prefix=True)
print(price)
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
hk = pd.DataFrame(price)
hk = hk.T.ix[:, ['name', 'now', 'open', 'close']]
price = hk.iterrows()
row = 0
for index, stock in price:
self.trigger.emit(f"{row}:{stock['name']}:{stock['now']}")
row += 1
except Exception as e:
print(e)
class MyApp(QMainWindow):
def __init__(self, stockIds, parent=None):
super(MyApp, self).__init__(parent)
self.stocks = stockIds
self.createTable()
self.timer = QTimer()
self.timer.setInterval(5000)
self.timer.timeout.connect(self.start)
self.timer.start()
self.work - 最佳的self 来源和相关信息。 = WorkThread()
self.work.trigger.connect(self.showPrice)
self.setCentralWidget(self.listView)
def start(self):
self.work.start()
def createTable(self):
self.listView = QTableWidget()
self.listView.setRowCount(10)
self.listView.setColumnCount(3)
for row, s in enumerate(self.stocks):
item = QTableWidgetItem()
item.setText(s)
self.listView.setItem(row, 0, item)
item = QTableWidgetItem()
item.setText("")
self.listView.setItem(row, 1, item)
item = QTableWidgetItem()
item.setText("")
self.listView.setItem(row, 2, item)
def showPrice(self, str):
print(f"got {str}")
row =int( str.split(':')[0])
name = str.split(':')[1]
price = str.split(':')[2]
self.listView.item(row, 1).setText(name)
self.listView.item(row, 2).setText(price)
def main():
app = QApplication(sys.argv)
t = MyApp(stocks)
www.8.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
感兴趣的同学就可以在后期分析这些数据,找出符合条件的股票再调用selenium或者pyautogui去下单,这就是传说中的量化交易了。说不定下一个股神就是你呢,加油!扫码关注公众号,获取更多文章