我正在尝试下载代码列表的历史数据并将每个数据导出到 csv 文件。我可以使它作为一个 for 循环工作,但是当股票代码列表在 1000 中时,这非常慢。我正在尝试对进程进行多线程处理,但我不断收到许多不同的错误。有时它只会下载 1 个文件,有时会下载 2 或 3 个文件,有时甚至会下载 6 个文件,但永远不会超过。我猜这与拥有 6 核 12 线程处理器有关,但我真的不知道。
import csv
import os
import yfinance as yf
import pandas as pd
from threading import Thread
ticker_list = []
with open('tickers.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
name = None
for row in reader:
if row[0]:
ticker_list.append(row[0])
start_date = '2019-03-03'
end_date = '2020-03-04'
data = pd.DataFrame()
def y_hist(i):
ticker = ticker_list[i]
data = yf.download(ticker, start=start_date, end=end_date, group_by="ticker")
data.to_csv('yhist/' + ticker + '.csv', sep=',', encoding='utf-8')
threads = []
for i in range(os.cpu_count()):
print('registering thread %d' % i)
threads.append(Thread(target=y_hist,args=(i,)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print('done')
这是 csv 的示例文件,其中包含足以测试这一点的代码。股票代码.csv
这些是我阅读并使用代码的页面,以尝试使其工作:
这是一个简化版本,它的输出可能有助于澄清问题。
import os
import pandas as pd
import yfinance as yf
from threading import Thread
ticker_list = ['IBM','MSFT','QQQ','SPY','FB','XLV','XLF','XLK','XLE','GTHX','IYR','ONE','ROG','OLED','GLD']
def y_hist():
for ticker in ticker_list:
print(ticker)
threads = []
for i in range(os.cpu_count()):
threads.append(Thread(target=y_hist))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
输出:
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
OLEDIBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
GLD
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
IBM
GLD
MSFT
ROG
OLED
GLD
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
IBM
MSFT
QQQ
SPY
IBM
MSFT
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
IBM
MSFT
QQQ
SPY
FB
XLV
XLF
XLK
XLE
GTHX
IYR
ONE
ROG
OLED
GLD
GLD