python - 如何使用 Python 获取币安 API 的所有价格历史记录?
问题描述
我一直在使用此脚本使用 Binance API 和此脚本从一些加密货币中获取价格: https ://steemit.com/python/@marketstack/how-to-download-historical-price-data-from-binance-与蟒蛇
问题是使用此脚本我无法控制日期范围:例如,我想选择 2015 年 12 月至 2020 年 12 月之间的期间范围,或者我想要任何加密货币交易的第一天的每日价格......等等
因此,我与您分享我正在使用的代码(从 steemit 代码复制并稍作修改)我该怎么做?
# https://steemit.com/python/@marketstack/how-to-download-historical-price-data-from-binance-with-python###
import requests
import json
import pandas as pd
import numpy as np
import datetime as dt
frequency = input("Please enter the frequency (1m/5m/30m/.../1h/6h/1d/ : ")
def get_bars(symbol, interval=frequency):
root_url = 'https://api.binance.com/api/v1/klines'
url = root_url + '?symbol=' + symbol + '&interval=' + interval
data = json.loads(requests.get(url).text)
df = pd.DataFrame(data)
df.columns = ['open_time',
'o', 'h', 'l', 'c', 'v',
'close_time', 'qav', 'num_trades',
'taker_base_vol', 'taker_quote_vol', 'ignore']
df.index = [dt.datetime.fromtimestamp(x / 1000.0) for x in df.close_time]
return df
btcusdt = get_bars('BTCUSDT')
ethusdt = get_bars('ETHUSDT')
df0=pd.DataFrame(btcusdt)
df0.to_csv('_btcusdt.csv')
df1=pd.DataFrame(ethusdt)
df1.to_csv('_ethusdt.csv')
谁能帮我优化一下?
解决方案
我在 binance 文档中使用了这个:https ://python-binance.readthedocs.io/en/latest/binance.html?highlight=get_historical_klines#binance.client.Client.get_historical_klines
import os
from binance.client import Client
import pandas as pd
import datetime, time
def GetHistoricalData(self, howLong):
self.howLong = howLong
# Calculate the timestamps for the binance api function
self.untilThisDate = datetime.datetime.now()
self.sinceThisDate = self.untilThisDate - datetime.timedelta(days = self.howLong)
# Execute the query from binance - timestamps must be converted to strings !
self.candle = self.client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, str(self.sinceThisDate), str(self.untilThisDate))
# Create a dataframe to label all the columns returned by binance so we work with them later.
self.df = pd.DataFrame(self.candle, columns=['dateTime', 'open', 'high', 'low', 'close', 'volume', 'closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol', 'takerBuyQuoteVol', 'ignore'])
# as timestamp is returned in ms, let us convert this back to proper timestamps.
self.df.dateTime = pd.to_datetime(self.df.dateTime, unit='ms').dt.strftime(Constants.DateTimeFormat)
self.df.set_index('dateTime', inplace=True)
# Get rid of columns we do not need
self.df = self.df.drop(['closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol','takerBuyQuoteVol', 'ignore'], axis=1)
print(self.df)
我希望这对某人有所帮助。
(请注意,此方法是从我的课程中删除的,因此您可能会摆脱所有的自我),并且您需要先设置您的客户端
client = Client(api_key, api_secret)
当然欢迎任何改进!
推荐阅读
- reactjs - 如何在 next.js(带有 react-native-web 支持)项目中重用 react-native 代码?
- maven - 如何使用带有管道的 Docker 缓存本地 Maven 存储库?
- java - 过度写入数组与删除并重新初始化它?爪哇
- javascript - 如何在 div 的单击而不是按钮上添加/删除 div 颜色?
- docker - 如何从 Docker 容器访问主机中的文件?
- angular - 如何使用 angular 7 和 bootstrap 4 逐步构建代码以形成表单?
- ruby-on-rails - 迭代合并的 AssociationRelation
- javascript - Angular 6:使用 .addControl 附加子表单组
- c++ - PCL 估计尖角处的法线给出弯曲的结果
- batch-file - 如果存在多个通配符