我正在尝试使用 YahooQuery 检索一些公司的季度收益,我已经能够获取全年的数据,但我想过滤这些数据以仅显示特定季度的结果。此外,我想将这些数据导出到 Excel 工作表并将其保存在那里以供所有公司使用。
import yahooquery
ticker = yahooquery.Ticker('AAPL',asynchronous=True)
ticker.earnings
我有一个类似的场景,试图提取 yahooquery 的嵌套字典,并在另一个问题上找到了有用的答案,这让我走上了正轨。
from yahooquery import Ticker
import pandas as pd
aapl = Ticker('aapl')
aaplInfo = aapl.earnings
这是我在另一篇 StackOverflow 帖子中找到的函数代码
def nested_dict_pairs_iterator(dict_obj):
''' This function accepts a nested dictionary as argument
and iterate over all values of nested dictionaries
'''
# Iterate over all key-value pairs of dict argument
for key, value in dict_obj.items():
# Check if value is of dict type
if isinstance(value, dict):
# If value is dict then iterate over all its values
for pair in nested_dict_pairs_iterator(value):
yield (key, *pair)
else:
# If value is not dict type then yield the value
yield (key, value)
在这里,我只是提取了您正在寻找的必要部分,并创建了一个 pandas 数据框以加载到 Excel 中
for pair in nested_dict_pairs_iterator(aaplInfo):
if (pair[1] == 'financialsChart' and pair[2] == 'quarterly'):
df = pd.DataFrame(pair[3])
df.to_excel('Stock_Earnings.xlsx', sheet_name='AAPL', index=False)