将从 REST 端点检索到的数据存储到 python 中的变量中

storing data retrieved from REST endpoint into variables in python

提问人:dom 提问时间:11/10/2023 更新时间:11/10/2023 访问量:32

问:

我正在尝试从 SEC EDGAR 数据库中检索数据,我得到了一个有效的端点 url,例如:https://data.sec.gov/submissions/CIK0000320193.json(这是 Apple Inc 的端点),但是当我尝试将结果存储在变量中时,我得到一个空列表:results = [],当我将结果保存在 txt 文件中时......井。。。该文件显然是空的,这是处理它的代码块:

def get_sec_data(cik):
    try:
        # Define the SEC data.gov API endpoint for fetching filings in JSON format
        endpoint = f"https://data.sec.gov/submissions/CIK{cik}.json"
# Print the API endpoint
        print("API Endpoint:", endpoint)

        # Define the headers with the required User-Agent
        headers = {
            'User-Agent': "dom dom [email protected]",
            'Accept-Encoding': 'gzip, deflate'
        }

     
        # Make a GET request to the SEC data.gov API with the specified headers
        response = requests.get(endpoint, headers=headers)

        # Check if the request was successful (status code 200)
        if response.status_code != 200:
            raise Exception(f"Failed to fetch SEC data. Status: {response.status_code}")

        # Parse the JSON response
        json_data = response.json()

        # Extract the XBRL data for the latest 10-K and 10-Q filings
        filings_data = json_data.get('hits', [])

        return filings_data

    except Exception as e:
        raise Exception(f"Error: {str(e)}")

然后我得到结果并尝试保存它

# Retrieve the last 10-K and 10-Q filings for the specified company in JSON format
try:
    results = get_sec_data(cik)
    # Display the results or handle errors
    for result in results:
        if "Error" in result:
            print(result)
        else:
            print("Successfully retrieved data from SEC data.gov API.")
            # You can now use the variable 'results' for further processing.

    # Specify the file name without a path
    file_name = "test.txt"

    # Construct the full file path by joining it with the current working directory
    file_path = "/users/domdom/desktop/Project/" + file_name

    # Open the file in write mode
    with open(file_path, 'w') as file:
        # Iterate over the results and write each entry to the file
        for entry in results:
            file.write(str(entry) + '\n')

    print(f"Data has been written to {file_path}")

except Exception as e:
    print(e)

我做错了什么?我尝试了不同的检查,看看我获得的端点链接是否正确,如果我从 SEC 网站检索数据,并且在浏览器中打开链接时一切正常,我还尝试保存 csv 而不是 txt,同样的事情:空。似乎问题出在存储然后从端点保存内容。

JSON python-3.x rest xbrl

评论


答:

0赞 Andrew Merrill 11/10/2023 #1

你想在这条线上做什么:?filings_data = json_data.get('hits', [])

您似乎正在尝试从 EDGAR 返回的 JSON 数据中获取属性的值,但据我所知,没有这样的属性。尝试获取不同的属性(例如,),您应该会得到更好的结果。hitstickers

评论

0赞 dom 11/10/2023
是的,你是对的,这是从 JSON 中获取任何内容的行,我仍在为 XBRL 格式而苦苦挣扎,我正在尝试检索和提取 10-K(完整财政年度)数据,如收入、长期债务等,并最终将其保存在专用变量中,以便使用这些数字进行计算。