Created
January 2, 2023 05:55
-
-
Save madawei2699/907235ba23fbbdac49241524ed2c75fc to your computer and use it in GitHub Desktop.
Get cryptocurrency year price history data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import csv | |
from datetime import datetime | |
# 设置 id 和 range 参数 | |
id = 1 # BTC | |
# id = 1027 # ETH | |
start = 2022 | |
end = 2022 + 1 | |
start_timestamp = int(datetime(start, 1, 1).timestamp()) | |
end_timestamp = int(datetime(end, 1, 1).timestamp()) | |
# 获取 API 数据 | |
url = 'https://api.coinmarketcap.com/data-api/v3/cryptocurrency/detail/chart' | |
params = { | |
'id': id, | |
'range': f'{start_timestamp}~{end_timestamp}' | |
} | |
response = requests.get(url, params=params) | |
# 解析数据 | |
data = response.json() | |
# 创建 csv 文件 | |
with open(str(id) + '.csv', 'w', newline='') as f: | |
writer = csv.writer(f) | |
# 写入 csv 文件的头 | |
writer.writerow(['date', 'v[0]', 'index']) | |
# 遍历 points | |
for timestamp, point in data['data']['points'].items(): | |
# 转换时间戳为日期 | |
date = datetime.fromtimestamp(int(timestamp)).strftime('%Y-%m-%d') | |
# 计算 index | |
index = round(point['v'][0] / data['data']['points'][next(iter(data['data']['points']))]['v'][0], 2) | |
# 写入 csv 文件 | |
writer.writerow([date, round(point['v'][0], 2), index]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment