The problem I'm having is that the continue
command is skipping inconsistently. It skips the numerical output ebitda
but puts the incorrect ticker
next to it. Why is this? If I make the ticker just phm
an input it should skip, it correctly prints an empty list []
but when an invalid ticker is placed next to a valid one, the confusion starts happening.
import requests
ticker = ['aapl', 'phm', 'mmm']
ebitda = []
for i in ticker:
r_EV=requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/'+i+'?formatted=true&crumb=8ldhetOu7RJ&lang=en-US®ion=US&modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&corsDomain=finance.yahoo.com')
r_ebit = requests.get('https://query1.finance.yahoo.com/v10/finance/quoteSummary/' + i + '?formatted=true&crumb=B2JsfXH.lpf&lang=en-US®ion=US&modules=incomeStatementHistory%2CcashflowStatementHistory%2CbalanceSheetHistory%2CincomeStatementHistoryQuarterly%2CcashflowStatementHistoryQuarterly%2CbalanceSheetHistoryQuarterly%2Cearnings&corsDomain=finance.yahoo.com%27')
data = r_EV.json()
data1 = r_ebit.json()
if data1['quoteSummary']['result'][0]['balanceSheetHistoryQuarterly']['balanceSheetStatements'][0].get('totalCurrentAssets') == None:
continue #skips certain ticker if no Total Current Assets available (like for PHM)
ebitda_data = data['quoteSummary']['result'][0]['financialData']
ebitda_dict = ebitda_data['ebitda']
ebitda.append(ebitda_dict['raw']) #navigates to dictionairy where ebitda is stored
ebitda_formatted = dict(zip(ticker, ebitda))
print(ebitda_formatted)
# should print {'aapl': 73961996288, 'mmm': 8618000384}
# NOT: {'aapl': 73961996288, 'phm': 8618000384}
The continue
works just fine. You produce this list:
[73961996288, 8618000384]
However, you then zip that list with ticker
, which still has 3 elements in it, including 'phm'
. zip()
stops when one of the iterables is empty, so you produce the following tuples:
>>> ebitda
[73961996288, 8618000384]
>>> ticker
['aapl', 'phm', 'mmm']
>>> zip(ticker, ebitda)
[('aapl', 73961996288), ('phm', 8618000384)]
If you are selectively adding ebitda
values to a list, you'd also have to record what ticker
values you processed:
used_ticker.append(i)
and use that new list.
Or you could just start with an empty ebitda_formatted
dictionary and add to that in the loop:
ebitda_formatted[i] = ebitda_dict['raw']