我对循环和API非常陌生。我目前正在试用IEX的沙箱来收集财务数据。我所做的是收集IEX支持的股票符号列表,然后使用该列表调用数据并将其附加到数据帧中。问题是,有些年IEX没有特定安全性的数据。我希望在数据帧中保持这种安全性,如果缺少值,就写N/A。我的循环代码如下:
my_columns = ['date','Ticker','Price','o_cash_flow','total_income',
'total_assets','total_liab','rev','ebit','ttm_eps',
'shares_out','profit_margin','total_rev','2year_return',
'1year_return','6month_return','3month_return','1month_return']
financials_df = pd.DataFrame(columns = my_columns)
for symbol_string in symbol_strings:
batch_api_call_url = f'{sandbox_url}/stable/stock/market/batch?symbols={symbol_string}&types=price,financials,stats,advanced-stats&range=2q&token={token}'
data = requests.get(batch_api_call_url).json()
for symbol in symbol_string.split(','):
print(data[symbol])
financials_df = financials_df.append(
pd.Series
[
data[symbol]['financials']['financials'][0]['fiscalDate'],
symbol,
data[symbol]['price'],
data[symbol]['financials']['financials'][0]['cashFlow'],
data[symbol]['financials']['financials'][0]['netIncome'],
data[symbol]['financials']['financials'][0]['totalAssets'],
data[symbol]['financials']['financials'][0]['totalLiabilities'],
data[symbol]['financials']['financials'][0]['revenue'],
data[symbol]['financials']['financials'][0]['ebit'],
data[symbol]['stats']['ttmEPS'],
data[symbol]['stats']['sharesOutstanding'],
data[symbol]['advanced-stats']['profitMargin'],
data[symbol]['advanced-stats']['totalRevenue'],
data[symbol]['stats']['year2ChangePercent'],
data[symbol]['stats']['year1ChangePercent'],
data[symbol]['stats']['month6ChangePercent'],
data[symbol]['stats']['month3ChangePercent'],
data[symbol]['stats']['month1ChangePercent']
],
index = my_columns),
ignore_index = True
)
然后,我收到一个错误“KeyError:‘financials’”,这是因为某些证券缺少第二次调用financials。我希望循环只在dataframe中用N/A替换数据,并在发生这种情况时继续从api调用数据。任何帮助都将不胜感激,谢谢。