使用stock_basic从tushare获取股票数据,从中提取股票代码,用此股票代码下载股票交易数据,打印总股票数量,下载花费时间,使用两个线程来下载,用threading.Thread模块,发送两个信号股票的总共的下载进度,下载进度是整数百分比,创建一个这样的类
时间: 2023-10-10 10:11:33 浏览: 142
stock-demo-Total股票数据集
以下是一个实现你所说功能的类:
```python
import threading
import time
import tushare as ts
class StockDownloader:
def __init__(self, start_date, end_date):
self.start_date = start_date
self.end_date = end_date
self.stock_codes = []
self.total_stock_num = 0
self.downloaded_stock_num = 0
self.progress1 = 0
self.progress2 = 0
self.lock = threading.Lock()
def get_stock_codes(self):
df = ts.get_stock_basics()
self.stock_codes = list(df.index)
self.total_stock_num = len(self.stock_codes)
def download_stock_data(self, start, end, thread_num):
for i in range(start, end):
code = self.stock_codes[i]
df = ts.get_hist_data(code, start=self.start_date, end=self.end_date)
with self.lock:
self.downloaded_stock_num += 1
if thread_num == 1:
self.progress1 = self.downloaded_stock_num / self.total_stock_num * 100
else:
self.progress2 = self.downloaded_stock_num / self.total_stock_num * 100
def download_stock_data_with_threads(self):
self.get_stock_codes()
mid = self.total_stock_num // 2
thread1 = threading.Thread(target=self.download_stock_data, args=(0, mid, 1))
thread2 = threading.Thread(target=self.download_stock_data, args=(mid, self.total_stock_num, 2))
start_time = time.time()
thread1.start()
thread2.start()
while thread1.is_alive() or thread2.is_alive():
time.sleep(1)
print(f"Progress 1: {round(self.progress1, 2)}%")
print(f"Progress 2: {round(self.progress2, 2)}%")
end_time = time.time()
print(f"Total downloaded stock num: {self.downloaded_stock_num}")
print(f"Time used: {end_time - start_time} seconds")
```
这个类有以下几个方法:
- `__init__`: 初始化,接收下载的起止日期。
- `get_stock_codes`: 从tushare中获取所有股票代码,计算股票总数。
- `download_stock_data`: 下载指定股票代码的交易数据,更新已下载股票总数和下载进度。
- `download_stock_data_with_threads`: 使用两个线程来下载股票数据,输出下载进度和花费时间。
使用示例:
```python
downloader = StockDownloader("2021-01-01", "2021-05-31")
downloader.download_stock_data_with_threads()
```
阅读全文