微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用金融建模准备 (Python) 访问具有指定时间间隔的所有历史加密数据

如何解决使用金融建模准备 (Python) 访问具有指定时间间隔的所有历史加密数据

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 数据(价值 1828 天,截至 2018 年 1 月 18 日),时间间隔为 1 天。例如,使用 Spyder 变量资源管理器:

enter image description here

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

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

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

enter image description here

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

解决方法

我知道这不是您正在寻找的确切解决方案,但这是另一种无需使用 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))

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。