[英]How do I combine multiple dataframes from a json file using an api and a for loop? (python)
I am trying to download financial ratio data for more than one company ticker and save the data to one data frame.我正在尝试下载多个公司代码的财务比率数据,并将数据保存到一个数据框中。 I have used a function to interact with the API and download the json file, then I am trying to make a for loop to iterate through the dictionary of tickers.
我使用了一个函数来与 API 交互并下载 json 文件,然后我尝试创建一个 for 循环来遍历股票行情字典。
api_key = 'API KEY REMOVED FOR PRIVACY'
def get_ratios(stock):
url = (f'https://financialmodelingprep.com/api/v3/ratios/{stock}?limit=40&apikey={api_key}')
x = pd.read_json(url)
return x
Using just the function get_ratios('AAPL') returns a dataframe, but I want to be able to retrieve data for multiple tickers, not just AAPL.仅使用函数 get_ratios('AAPL') 返回一个数据帧,但我希望能够检索多个代码的数据,而不仅仅是 AAPL。
I have tried to create a for loop to be able to retrieve data for multiple tickers.
我试图创建一个 for 循环以便能够检索多个股票代码的数据。 When I try save the function to a dataframe only the data for AAN saves.. so I think it must be overwriting the data for AAPL.
当我尝试将函数保存到数据帧时,只有 AAN 的数据会保存..所以我认为它必须覆盖 AAPL 的数据。 I am unsure how to fix this, I have tried to create another for loop to .append the dataframe y to itself, but I just get an error back.
我不确定如何解决这个问题,我尝试创建另一个 for 循环来将数据帧 y 附加到自身,但我只是得到一个错误。
ticker = ['AAPL','AAN']
for i in ticker:
y = get_ratios(i)
But when I don't save get_ratios(i) to a list and run it as shown below, I get a list of both AAPL and AAN data.但是,当我不将 get_ratios(i) 保存到列表并按如下所示运行它时,我会得到 AAPL 和 AAN 数据的列表。
ticker = ['AAPL','AAN']
for i in ticker:
print(get_ratios(i))
symbol date period currentRatio quickRatio cashRatio交易品种 日期 周期 currentRatio quickRatio cashRatio
0 AAPL 2020-09-26 FY 1.363604 1.218195 0.360710 0 AAPL 2020-09-26 财年 1.363604 1.218195 0.360710
1 AAPL 2019-09-28 FY 1.540126 1.384447 0.462022 1 AAPL 2019-09-28 财年 1.540126 1.384447 0.462022
2 AAPL 2018-09-29 FY 1.123843 0.986566 0.221733 2 AAPL 2018-09-29 财年 1.123843 0.986566 0.221733
3 AAPL 2017-09-30 FY 1.276063 1.089670 0.201252 3 苹果 2017-09-30 财年 1.276063 1.089670 0.201252
Put the dataframes returnet by get_ratios()
to a list and as a final step do pd.concat
to concat the dataframes to one.将
get_ratios()
返回的数据帧放入一个列表,并作为最后一步执行pd.concat
将数据帧pd.concat
为一个。 For example:例如:
ticker = ["AAPL", "AAN"]
df_list = []
for i in ticker:
df_list.append(get_ratios(i))
df_final = pd.concat(df_list)
在使用列表理解和pd.concat
,您可以执行以下操作:
df = pd.concat([get_ratios(t) for t in ticker])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.