从多边形 api 转储 json 响应的有效方法是什么?

What is an efficient way to dump a json response from polygon api?

我正在从 polygon api and after checking the documentation 下载数据,我意识到在响应大小方面存在某种速率限制,每个请求包含 5000 条记录。假设我需要下载几个月的数据,看起来没有一次性的解决方案可以一次获取指定时间段内的所有数据。

这是我使用 requests.get('query').json():

获得的 4 天数据点的响应
{
   "ticker":"AAPL",
   "status":"OK",
   "queryCount":4,
   "resultsCount":4,
   "adjusted":True,
   "results":[
      {
         "v":152050116.0,
         "vw":132.8458,
         "o":132.76,
         "c":134.18,
         "h":134.8,
         "l":130.53,
         "t":1598932800000,
         "n":1
      },
      {
         "v":200117202.0,
         "vw":131.6134,
         "o":137.59,
         "c":131.4,
         "h":137.98,
         "l":127,
         "t":1599019200000,
         "n":1
      },
      {
         "v":257589206.0,
         "vw":123.526,
         "o":126.91,
         "c":120.88,
         "h":128.84,
         "l":120.5,
         "t":1599105600000,
         "n":1
      },
      {
         "v":336546289.0,
         "vw":117.9427,
         "o":120.07,
         "c":120.96,
         "h":123.7,
         "l":110.89,
         "t":1599192000000,
         "n":1
      }
   ],
   "request_id":"bf5f3d5baa930697621b97269f9ccaeb"
}

我认为最快的方法是按原样编写内容,稍后再处理

with open(out_file, 'a') as out:
    out.write(f'{response.json()["results"][0]}\n')

稍后在我下载我需要的内容后,将读取文件并使用 pandas:

将数据转换为 json 文件
pd.DataFrame([eval(item) for item in open('out_file.txt')]).to_json('out_file.json')

有没有更好的方法来实现同样的目标?如果有人熟悉 scrapy 提要导出,有没有办法在 运行 期间将数据转储到 json 文件而不将任何内容保存到内存中,我认为这与 scrapy 操作的方式相同。

与其将内容写成文本,不如直接将其写成 JSON 而不是使用唯一的文件名(例如您的 request_id)。

import json

# code for fetching data omitted.
data = response.json()

with open(out_file, 'w') as f:
    json.dump(data, f)

然后你可以将它们全部加载到Dataframes中,例如类似于此处::

from pathlib import Path # Python 3.5+

import pandas as pd

dfs = []

for path in Path('dumped').rglob('*.json'):
    tmp = pd.read_json(path)
    dfs.append(tmp)

df = pd.concat(dfs, ignore_index=True)