【问题标题】:Accessing all historical crypto data with specified time interval using Financial Modeling Prep (Python)使用 Financial Modeling Prep (Python) 以指定的时间间隔访问所有历史加密数据
【发布时间】:2021-04-23 03:09:56
【问题描述】:

Financial Modeling Prep 是一个免费的 API,可用于访问各种财务指标,例如股票价格和加密货币数据。 API 文档概述了如何通过 Python 等编程语言访问数据。特别是对于加密货币数据:

https://financialmodelingprep.com/developer/docs/#Historical-Cryptocurrencies-Price

只需生成唯一的 API 密钥,即可通过调用 URL 访问数据。 URL 的内容被接收并解析为 JSON,并在 Python 中作为对象返回。例如,我可以访问比特币的所有历史数据(价格、交易量、低点、高点等):

try:
# For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json

def get_jsonparsed_data(url):

    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url = ("https://financialmodelingprep.com/api/v3/historical-price-full/crypto/BTCUSD?apikey=myKey")

myData = get_jsonparsed_data(url)

默认情况下,通过此 URL 调用,对象包含所有 BTC 数据(截至 21 年 1 月 18 日,价值 1828 天),时间间隔为 1 天。例如,使用 Spyder 变量资源管理器:

但是,我想将时间分辨率提高到 4 小时。 API 文档提供了有关如何执行此操作的一些见解 - 只需将 url 更改为以下内容:

url = ("https://financialmodelingprep.com/api/v3/historical-chart/4hour/BTCUSD?apikey=myKey")

结果是每 4 小时采样一次的 BTC 数据。但是,只有200个数据点,限制了历史数据的范围:

查看文档后,不清楚如何指定 4 小时间隔以及所有历史数据(所以我会得到 6*1828 = 10968 个数据点)。如何获取感兴趣的时间间隔内的所有数据?

【问题讨论】:

    标签: python url finance


    【解决方案1】:

    我知道这不是您正在寻找的确切解决方案,但这是您无需使用 API 即可从 coinmarketcap.com 获取历史加密价格的另一种方法:

    # use urllib to get HTML data
    url = "https://coinmarketcap.com/historical/20201206/"
    contents = urllib.request.urlopen(url)
    bytes_str = contents.read()
    
    # decode bytes string
    data_str = bytes_str.decode("utf-8")
    
    # crop the raw JSON string out of the website HTML
    start_str = '"listingHistorical":{"data":'
    start = data_str.find(start_str)+len(start_str)
    end = data_str.find(',"page":1,"sort":""')
    cropped_str = data_str[start:end]
    
    # create a Python list from JSON string
    data_list = json.loads(cropped_str)
    print ("total cryptos:", len(data_list))
    
    # iterate over the list of crypto dicts
    for i, item in enumerate(data_list):
    
        # pretty print all cryptos with a high rank
        if item["cmc_rank"] < 30:
            print (json.dumps(item, indent=4))
    
    

    要从另一个日期获取不同的数据,只需将 URL 中的 20201206 部分替换为首选日期(例如,使用 20210110 代替 2021 年 1 月 10 日)。

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2012-04-04
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多