Reputation: 51
I am using python and the yahoo api to get next earnings date for specified individual stocks from yahoo finance. Following link is info about using yahoo_fin: http://theautomatic.net/yahoo_fin-documentation/#get_next_earnings_date Also pasted below is the python script I am using. It basically gets the ticker symbols from an excel sheet and returns the next earnings date for the ticker. It works fine if all the tickers in the list have a next earnings date. However, as soon as it hits a ticker in the list that has no next earnings date (i.e. shows as N/A on yahoo finance page), the script throws up an error (also shown below. actually a link as I am apparently not allowed to attach images yet!) and ends the process. Would appreciate a solution or workaround to this problem please. Thank you.
import yahoo_fin.stock_info as si
import pandas as pd
import xlwings as xw
wb = xw.Book("StockScreener.xlsm")
ws1 = wb.sheets["Tickers"]
#code to get number of rows with data
rownum = 3
maxRow = 3
while (ws1.range('B'+str(rownum)).value != None):
maxRow += 1
rownum += 1
for ticker_row in range(3, maxRow):
ticker_symbol = ws1.cells(ticker_row, 2).value
tickerEarnings = si.get_next_earnings_date(ticker_symbol)
print(ticker_symbol,tickerEarnings)
Image of print out when code is run:
Text of printout (if unable to view image) below, but not aligned well though:
IMGN 2021-11-04 12:30:00
CAN 2021-11-29 13:30:00
NRXP 2021-11-15 21:00:00
HIMS 2021-08-11 21:00:00
ENLC 2021-11-02 20:00:00
CLOV 2021-08-11 21:00:00
MRIN 2021-11-03 10:59:00
Traceback (most recent call last):
File "C:\Users\Kay\PycharmProjects\StockScreener\EarningsYahoo.py", line 19, in <module>
tickerEarnings = si.get_next_earnings_date(ticker_symbol)
File "C:\Users\Kay\AppData\Local\Programs\Python\Python310\lib\site-packages\yahoo_fin\stock_info.py", line 823, in get_next_earnings_date
temp = parsed_result['context']['dispatcher']['stores']['QuoteSummaryStore']['calendarEvents']['earnings']['earningsDate'][0]['raw']
IndexError: list index out of range
Process finished with exit code 1
Upvotes: 0
Views: 5716
Reputation: 142631
As you said problem is that some symbols have no earningsDate
.
When get_next_earnings_date()
tries to get ['earningsDate'][0]['raw']
then it can't get [0]
and this raise error index range
because there is no element with index 0
.
It has nothing to do with your command range()
.
Standard method is to use try/except
to catch error and do something with this problem - ie. you can skip data for this symbol.
Minimal working example
import yahoo_fin.stock_info as si
for ticker_symbol in ['IMGN', 'DIDI']:
print('Symbol:', ticker_symbol)
try:
tickerEarnings = si.get_next_earnings_date(ticker_symbol)
print('Earnings:', tickerEarnings)
except Exception as ex:
print('[Exception]', ex)
print('Earnings: skiping this symbol')
Result:
Symbol: IMGN
Earnings: 2021-11-04 13:30:00
Symbol: DIDI
[Exception] list index out of range
Earnings: skiping this symbol
Upvotes: 1