我遇到的问题是continue
命令的跳过不一致。它跳过数值输出ebitda
,但将不正确的ticker
放在它旁边。为什么会这样?如果我让ticker只是phm
一个它应该跳过的输入,它会正确地打印一个空列表[]
,但是当一个无效的ticker放在一个有效的ticker旁边时,混乱就开始发生了。你知道吗
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}
continue
工作正常。您将生成以下列表:但是,然后用
ticker
压缩该列表,其中仍然有3个元素,包括'phm'
。zip()
在其中一个iterable为空时停止,因此生成以下元组:如果要有选择地向列表中添加
ebitda
值,还必须记录处理的ticker
值:使用新列表。你知道吗
或者您可以用一个空的
ebitda_formatted
字典来启动,并将其添加到循环中:相关问题 更多 >
编程相关推荐