Mar*_*ams 0 python finance pandas 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)
Run Code Online (Sandbox Code Playgroud)
这种方法目前非常慢,并且一次接收一个信息,因此无论如何都可以使其更快和/或批量获取股票信息。
我还尝试使用 yf.download 方法一次下载多个股票的信息,这速度更快,但我无法从中获取我想要的信息,因此是否可以使用 yf 获取市值和当前价格.下载方法?
虽然也有类似的问题,但它们似乎都使用了我使用的相同的一般思想,当股票数量很高时,这需要很长时间,我还没有找到任何比我当前的解决方案更快的解决方案,因此,任何建议都值得赞赏,即使是不使用 yfinance 的解决方案,只要它们能够获得实时数据而不会出现严重延迟。
小智 7
您可以尝试另一个名为 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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8187 次 |
最近记录: |