我正在测试一个具有api的服务,该api可以从中提取解析的10K公司数据。对于提取的每个指标(息税前利润、现金、总资产等),我将季度日期和指标存储在一个元组中,并将每个元组存储在一个列表中。结果是6个43-80元组的列表。我想要一个带有公司股票代码、日期和指标列的数据框架。我如何将我拥有的(元组列表)转换成那个
下面的代码用于提取数据(这是示例,因此不收费):
import numpy as np
import json
import pandas as pd
content = requests.get(r'https://eodhistoricaldata.com/api/fundamentals/AAPL.US?api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX')
ebit_list = []
date_list = []
totalassets_list = []
cash_list = []
totalCurrentAssets_list = []
totalCurrentLiabilities_list = []
for i in content.json()['Financials']['Income_Statement']['quarterly']:
try:
ebit_list.append((i, float(content.json()['Financials']['Income_Statement']['quarterly'][i]['ebit'])))
except:
pass
try:
date_list.append(i)
except:
pass
try:
totalassets_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['totalAssets'])))
except:
pass
for i in content.json()['Financials']['Balance_Sheet']['quarterly']:
#print(i, float(content.json()['Financials']['Balance_Sheet']['quarterly']['2019-12-28']['totalCurrentLiabilities']))
try:
cash_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['cash'])))
except:
pass
try:
totalCurrentAssets_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['totalCurrentAssets'])))
except:
pass
try:
totalCurrentLiabilities_list.append((i, float(content.json()['Financials']['Balance_Sheet']['quarterly'][i]['totalCurrentLiabilities'])))
except:
pass
我想要一个包含所有日期的数据框(意味着如果缺少一个度量,则填写一个零)和以下列:
date
,ebit
,totalassets
,cash
,totalCurrentAssets
,totalCurrentLiabilities
我不知道如何提取元组和每个元组中的值
您可以使用} 函数将日期与所需的数据进行匹配。这将为没有匹配值的单元格插入}
pandas.Series
中的^{NaN
,这将使以后更容易处理丢失的数据。如果仍然要填充零,可以使用^{ignore_index
中的sort_values
参数用于确保排序后索引不会混乱。如果pandas
版本是旧版本,则排序时可能会给出TypeError: sort_values() got an unexpected keyword argument 'ignore_index'
。如果是这样的话,您应该使用以下方法来重置索引最后是df
我无法让您的示例工作,请求未定义
但这里有一些代码可以满足您的要求:
实际上,我们可以大大简化此代码,以获得所需的结果(并使其在将来更易于调整!)
完成的代码在这里,更详细的解释如下:
财务数据框架如下所示(仅显示2005-2009年的数据):
content.json()['Financials']['Income_Statement']['quarterly']
的结果是一个字典,每个键都是日期,每个值都是第二个字典,其中包含列数据由于是这种情况,您实际上可以使用
pd.DataFrame.from_dict(income_data).transpose().set_index("date")
由于JSON的结构,转置是必要的。Pandas需要一个格式为
{'column name': data}
的字典。由于键是日期,您将首先获得一个数据框,其中行标记为“totalAssets”、“cash”等,列为日期。transpose()
命令翻转行和列,使其符合您需要的格式最后一个.set_index("date")
命令用于使用“日期”数据而不是初始键日期,以保持一致性并命名索引。它是完全可选的现在,这个数据框架将包含JSON文件中的每一列,但您只对其中的几列感兴趣。代码
income = income[['ebit']]
仅从数据中选择相关列
由于要从两个不同的源提取数据,因此确实需要创建两个不同的表。这还有一个额外的好处,那就是你可以更清楚地看到哪些栏目是从“损益表”中提取出来的,哪些栏目是从“资产负债表”中提取出来的
最后一行
financials = income.merge(balance, left_index = True, right_index = True).fillna(0)
使用索引(在本例中为“日期”列)将两个表合并在一起
fillna(0)
确保按照您的请求,用零值替换任何缺失的数据如果您最终需要添加另一个表,例如“现金流”,您可以使用相同的代码行创建该表并选择相关列,然后添加第二个合并行:
作为一个额外提示,源JSON中有相当多的数据!要查看任何给定表中的可用列,请使用以下命令:
cashflow.columns.sort_values()
要获取按字母顺序排列的列列表,可以使用:
当数据中出现拼写错误时,如上面的“capitalSurpluse”中,这也非常有用
相关问题 更多 >
编程相关推荐