问题
I wrote the code below and it is running. When the loop run a fourth time, it gives an error. It gives "IndexError: list index out of range". How do I fix this error?
import yfinance as yf
dow_list = ['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DIS', 'DOW', 'GS', 'HD', 'IBM', 'INTC', 'JNJ', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'RTX', 'TRV', 'UNH', 'V', 'VZ', 'WBA', 'WMT', 'XOM']
rows = []
for ticker in dow_list:
stk_container = yf.Ticker(ticker)
stk_info = stk_container.info
print(stk_info)
Traceback
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-140-46a177e9173f> in <module>
5 for ticker in dow_list:
6 stk_container = yf.Ticker(ticker)
----> 7 stk_info = stk_container.info
8 print(stk_info)
e:\Anaconda3\lib\site-packages\yfinance\ticker.py in info(self)
136 @property
137 def info(self):
--> 138 return self.get_info()
139
140 @property
e:\Anaconda3\lib\site-packages\yfinance\base.py in get_info(self, proxy, as_dict, *args, **kwargs)
413
414 def get_info(self, proxy=None, as_dict=False, *args, **kwargs):
--> 415 self._get_fundamentals(proxy)
416 data = self._info
417 if as_dict:
e:\Anaconda3\lib\site-packages\yfinance\base.py in _get_fundamentals(self, kind, proxy)
284 holders = _pd.read_html(url)
285 self._major_holders = holders[0]
--> 286 self._institutional_holders = holders[1]
287 if 'Date Reported' in self._institutional_holders:
288 self._institutional_holders['Date Reported'] = _pd.to_datetime(
IndexError: list index out of range
回答1:
- For 8 of the tickers, the
yfinance.ticker.Ticker
object,stk_container.info
results in an error when there is only 1 holder. This is a bug. - yfinance: Index out of range: some Tickers #208
- Use a
try-except
block to catch the exception.- Python: Errors and Exceptions
- You may fix the
yfinance
codebase with YFinance - tickerData.info not working for some stocks
import yfinance as yf
dow_list = ['AAPL', 'AXP', 'BA', 'CAT', 'CSCO', 'CVX', 'DIS', 'DOW', 'GS', 'HD', 'IBM', 'INTC', 'JNJ', 'JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'RTX', 'TRV', 'UNH', 'V', 'VZ', 'WBA', 'WMT', 'XOM']
rows = []
for ticker in dow_list:
stk_container = yf.Ticker(ticker)
try:
stk_info = stk_container.info
print(stk_info) # print the info
except IndexError as e:
print(f'{ticker}: {e}') # print the ticker and the error
print('\n')
来源:https://stackoverflow.com/questions/63662791/yfinance-indexerror-list-index-out-of-range