国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現(xiàn)多線程行情抓取工具的方法

2020-02-22 23:20:01
字體:
供稿:網(wǎng)友

思路

借助python當中threading模塊與Queue模塊組合可以方便的實現(xiàn)基于生產(chǎn)者-消費者模型的多線程模型。Jimmy大神的tushare一直是廣大python數(shù)據(jù)分析以及業(yè)余量化愛好者喜愛的免費、開源的python財經(jīng)數(shù)據(jù)接口包。

平時一直有在用阿里云服務(wù)器通過tushare的接口自動落地相關(guān)財經(jīng)數(shù)據(jù),但日復權(quán)行情數(shù)據(jù)以往在串行下載的過程當中,速度比較慢,有時遇到網(wǎng)絡(luò)原因還需要重下。每只股票的行情下載過程中都需要完成下載、落地2個步驟,一個可能需要網(wǎng)絡(luò)開銷、一個需要數(shù)據(jù)庫mysql的存取開銷。2者原本就可以獨立并行執(zhí)行,是個典型的“生產(chǎn)者-消費者”模型。

基于queue與threading模塊的線程使用一般采用以下的套路:

producerQueue=Queue()consumerQueue=Queue()lock = threading.Lock()class producerThead(threading.Thread): def __init__(self, producerQueue,consumerQueue): self.producerQueue=producerQueue self.consumerQueue=consumerQueue def run(self): while not self.thread_stop:  try:  #接收任務(wù),如果連續(xù)20秒沒有新的任務(wù),線程退出,否則會一直執(zhí)行  item=self.producerQueue.get(block=True, timeout=20)  #阻塞調(diào)用進程直到有數(shù)據(jù)可用。如果timeout是個正整數(shù),  #阻塞調(diào)用進程最多timeout秒,  #如果一直無數(shù)據(jù)可用,拋出Empty異常(帶超時的阻塞調(diào)用)  except Queue.Empty:  print("Nothing to do!thread exit!")  self.thread_stop=True  break  #實現(xiàn)生產(chǎn)者邏輯,生成消費者需要處理的內(nèi)容 consumerQueue.put(someItem)  #還可以邊處理,邊生成新的生產(chǎn)任務(wù)  doSomethingAboutProducing()  self.producerQueue.task_done() def stop(self): self.thread_stop = Trueclass consumerThead(threading.Thread): def __init__(self,lock, consumerQueue): self.consumerQueue=consumerQueue def run(self): while true:  try:  #接收任務(wù),如果連續(xù)20秒沒有新的任務(wù),線程退出,否則會一直執(zhí)行  item=self.consumerQueue.get(block=True, timeout=20)  #阻塞調(diào)用進程直到有數(shù)據(jù)可用。如果timeout是個正整數(shù),  #阻塞調(diào)用進程最多timeout秒,  #如果一直無數(shù)據(jù)可用,拋出Empty異常(帶超時的阻塞調(diào)用)  except Queue.Empty:  print("Nothing to do!thread exit!")  self.thread_stop=True  break  doSomethingAboutConsuming(lock)# 處理消費者邏輯,必要時使用線程鎖 ,如文件操作等  self.consumerQueue.task_done()#定義主線程def main(): for i in range(n):#定義n個i消費者線程 t = ThreadRead(producerQueue, consumerQueue) t.setDaemon(True) t.start() producerTasks=[] #定義初始化生產(chǎn)者任務(wù)隊列 producerQueue.put(producerTasks) for i in range(n):#定義n個生產(chǎn)者錢程 t = ThreadWrite(consumerQueue, lock) t.setDaemon(True) t.start()  stock_queue.join() data_queue.join()

相關(guān)接口

1,股票列表信息接口

作用

獲取滬深上市公司基本情況。屬性包括:

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 古丈县| 腾冲县| 曲松县| 平罗县| 桐庐县| 斗六市| 宜章县| 十堰市| 吉木乃县| 汶川县| 元氏县| 南城县| 长宁区| 广东省| 乌拉特中旗| 同心县| 赞皇县| 重庆市| 镇远县| 河源市| 呼伦贝尔市| 绩溪县| 阆中市| 牡丹江市| 邻水| 新源县| 大方县| 逊克县| 凉山| 保定市| 东丰县| 山西省| 宁安市| 静安区| 于田县| 广汉市| 顺平县| 定远县| 丁青县| 泰兴市| 子洲县|