簡體   English   中英

使用 yfinance 快速獲取多個股票代碼的信息

[英]Get info on multiple stock tickers quickly using yfinance

我正在嘗試獲取 S&P500 中所有股票代碼的當前價格和市值,而我目前這樣做的方式非常緩慢,所以我想知道是否有什么可以改進它的方法,或者任何其他方法. 這是我目前的方法,只是打印名稱、市值和當前價格:

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 獲得市值和當前價格.下載方法?

盡管有類似的問題,但他們似乎都使用了我使用的相同的一般想法,當代碼數量很多時,這需要很長時間,我還沒有找到任何比我目前更快的解決方案,因此,任何建議都會受到贊賞,即使是不使用 yfinance 的解決方案,只要它們能夠在沒有大量延遲的情況下獲得實時數據。

您可以嘗試另一個名為 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 {} 字典中還有很多其他信息,請查看。

您可能會發現,在離散線程中獲取單個代碼的值將為您提供更好的整體性能。 這是一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM