使用stock_basic从tushare获取股票数据,从中提取股票代码,用此股票代码下载股票交易数据,打印总股票数量,下载花费时间,使用两个线程来下载,发送两个信号股票的总共的下载进度,
时间: 2023-10-09 07:08:52 浏览: 32
以下是代码实现:
```python
import tushare as ts
import time
import threading
import signal
# 信号量,用于记录下载进度
total_progress = 0
finished_progress = 0
# 处理 Ctrl+C 退出信号
def signal_handler(sig, frame):
print("Download process stopped.")
exit(0)
# 从 tushare 获取所有股票代码
stock_list = ts.get_stock_basics().index.tolist()
# 定义线程类
class DownloadThread(threading.Thread):
def __init__(self, thread_id, stock_codes):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.stock_codes = stock_codes
def run(self):
global finished_progress
start_time = time.time()
for stock_code in self.stock_codes:
# 从 tushare 下载股票数据
df = ts.get_hist_data(stock_code)
if df is not None:
# 统计下载进度
finished_progress += 1
# 打印下载进度
print("Thread %d: Download progress %.2f%%" % (self.thread_id, finished_progress / total_progress * 100))
end_time = time.time()
print("Thread %d finished, time cost: %.2f seconds" % (self.thread_id, end_time - start_time))
# 处理信号
signal.signal(signal.SIGINT, signal_handler)
# 记录股票数量
total_progress = len(stock_list)
# 创建两个线程,分别下载股票数据
thread1 = DownloadThread(1, stock_list[:len(stock_list)//2])
thread2 = DownloadThread(2, stock_list[len(stock_list)//2:])
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
print("Total stocks downloaded: %d" % finished_progress)
```
该程序首先从 tushare 中获取所有股票代码,然后创建两个线程来下载股票数据。每个线程负责下载一部分股票数据,并记录下载进度。程序还使用信号量来处理 Ctrl+C 退出信号,以便在退出程序时清理资源。最后输出总共下载的股票数量。