我正试图获得标准普尔500指数所有股票的当前价格和市值,而我目前的做法非常缓慢,所以我想知道我是否可以做些什么来改进它,或者任何其他方法。以下是我当前的方法,只需打印名称、市值和当前价格:
import yfinance as yf
#I am using a csv file with a list of all the tickers which I use to create a pandas dataframe and form a space seperated string of all of the tickers called all_symbols
#I have simplified the pandas dataframe to a list for the purpose of this question
ticker_list = ["A", "AL", "AAP", "AAPL", ... "ZBRA", "ZION", "ZTS"]
all_symbols = " ".join(ticker_list)
tickers = yf.Tickers(all_symbols)
for ticker in ticker_list:
price = tickers.tickers[ticker].info["currentPrice"]
market_cap = tickers.tickers[ticker].info["marketCap"]
print(ticker, market_cap, price)
此方法目前非常慢,信息一次只接收一次,因此无论如何也是为了使其更快和/或获得批次的代码信息。
我也尝试过使用yf.download方法一次下载多个股票的信息,这样速度更快,但我无法从中获得我想要的信息,那么用yf.download方法是否有可能获得市值和当前价格呢?
虽然有类似的问题,但他们似乎都使用了我所使用的相同的一般想法,当代码数量很高时,需要很长时间,我还没有找到任何比我现在的解决方案更快的解决方案,所以任何建议都会受到赞赏,即使是不使用yfinance的解决方案,只要它们不需要大量延迟就能得到实时数据。
发布于 2022-02-17 16:59:42
您可能会发现,在一个离散线程中获取单个滴答的值将给您提供更好的总体性能。下面是一个例子:
import yfinance as yf
from concurrent.futures import ThreadPoolExecutor
def get_stats(ticker):
info = yf.Tickers(ticker).tickers[ticker].info
print(f"{ticker} {info['currentPrice']} {info['marketCap']}")
ticker_list = ['AAPL', 'ORCL', 'PREM.L', 'UKOG.L', 'KOD.L', 'TOM.L', 'VELA.L', 'MSFT', 'AMZN', 'GOOG']
with ThreadPoolExecutor() as executor:
executor.map(get_stats, ticker_list)
输出:
VELA.L 0.035 6004320
UKOG.L 0.1139 18496450
PREM.L 0.461 89516976
ORCL 76.755 204970377216
MSFT 294.8669 2210578825216
TOM.L 0.604 10558403
KOD.L 0.3 47496900
AMZN 3152.02 1603886514176
AAPL 171.425 2797553057792
GOOG 2698.05 1784584732672
发布于 2022-05-04 08:04:29
您可以尝试另一个名为yahooquery的库。在我的审判中,时间从34秒减少到0.4秒。
from yahooquery import Ticker
ticker_list = ["A", "AL", "AAP", "AAPL", "ZBRA", "ZION", "ZTS"]
all_symbols = " ".join(ticker_list)
myInfo = Ticker(all_symbols)
myDict = myInfo.price
for ticker in ticker_list:
ticker = str(ticker)
longName = myDict[ticker]['longName']
market_cap = myDict[ticker]['marketCap']
price = myDict[ticker]['regularMarketPrice']
print(ticker, longName, market_cap, price)
myDict {}字典中还有很多其他信息,请查看它。
https://stackoverflow.com/questions/71161902
复制相似问题