【问题标题】:What is an efficient way to dump a json response from polygon api?什么是从多边形 api 转储 json 响应的有效方法?
【发布时间】:2020-12-25 13:50:09
【问题描述】:

我正在从polygon api 下载数据,在检查了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 feed 导出,有没有办法在运行期间将数据转储到 json 文件而不将任何内容保存到内存中,我认为这与 scrapy 操作的方式相同。

【问题讨论】:

    标签: python json io python-requests


    【解决方案1】:

    不要将内容写为文本,而是直接将其写为 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 中,例如类似于这里:How to read multiple json files into pandas dataframe?:

    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)
    
    

    【讨论】:

    • 我记得做过类似的事情,我得到 json 抱怨某些类型冲突,你确保它有效吗?考虑到这个序列将被调用数千次,如果不是数百万次,你认为这会比我做的方式更快吗?它会附加到 json 文件中吗?
    • 您实际上需要确保您的数据不重复,因此您可能需要将其保存在某个地方。关于更快:限制因素是网络调用,如果您受到速率限制,则更是如此。所以没关系。
    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 2013-10-03
    • 2016-09-12
    • 2010-09-20
    • 2019-10-04
    • 2017-08-16
    相关资源
    最近更新 更多