首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过使用Python的加密的binance API获取所有价格历史?

如何通过使用Python的加密的binance API获取所有价格历史?
EN

Stack Overflow用户
提问于 2021-02-21 02:34:31
回答 3查看 14.9K关注 0票数 3

我一直在使用这个脚本通过Binance API和这个脚本从一些加密货币中获取价格:https://steemit.com/python/@marketstack/how-to-download-historical-price-data-from-binance-with-python

问题是,使用此脚本我无法控制日期范围:例如,我想要选择2015年12月和2020年12月之间的期间范围,或者我想要任何加密...etc的第一天交易的每日价格。

所以我与你分享我正在使用的代码(从steemit代码复制并稍微修改一下),我该怎么做呢?

代码语言:javascript
运行
复制
# 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')

有没有人能帮我优化一下?

EN

回答 3

Stack Overflow用户

发布于 2021-07-29 18:36:38

我在binance文档之外使用了这个:https://python-binance.readthedocs.io/en/latest/binance.html?highlight=get_historical_klines#binance.client.Client.get_historical_klines

代码语言:javascript
运行
复制
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)

我真的希望这能帮助到一些人。

(请注意,这个方法是从我的一个类中切出来的,所以你可以去掉所有的self-s),并且你需要在之前设置你的客户端。

client = Client(api_key, api_secret)

当然,任何改进都是欢迎的!

票数 6
EN

Stack Overflow用户

发布于 2021-02-21 03:50:48

这是我用过的一个函数。开始和结束是Unix时间戳格式的日期。interval是图形间隔。

请记住,Binance在2015年12月并不存在:-)

代码语言:javascript
运行
复制
def get_klines_iter(symbol, interval, start, end, limit=5000):
    df = pd.DataFrame()
    startDate = end
    while startDate>start:
        url = 'https://api.binance.com/api/v3/klines?symbol=' + \
            symbol + '&interval=' + interval + '&limit='  + str(iteration)
        if startDate is not None:
            url += '&endTime=' + str(startDate)
        
        df2 = pd.read_json(url)
        df2.columns = ['Opentime', 'Open', 'High', 'Low', 'Close', 'Volume', 'Closetime', 'Quote asset volume', 'Number of trades','Taker by base', 'Taker buy quote', 'Ignore']
        df = pd.concat([df2, df], axis=0, ignore_index=True, keys=None)
        startDate = df.Opentime[0]   
    df.reset_index(drop=True, inplace=True)    
    return df 
票数 3
EN

Stack Overflow用户

发布于 2021-11-20 13:26:53

代码语言:javascript
运行
复制
from binance.client import Client
from datetime import datetime
import pandas as pd

def GetHistoricalData(symbol, interval, fromDate, toDate):
    klines = client.get_historical_klines(symbol, interval, fromDate, toDate)
    df = pd.DataFrame(klines, columns=['dateTime', 'open', 'high', 'low', 'close', 'volume', 'closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol', 'takerBuyQuoteVol', 'ignore'])
    df.dateTime = pd.to_datetime(df.dateTime, unit='ms')
    df['date'] = df.dateTime.dt.strftime("%d/%m/%Y")
    df['time'] = df.dateTime.dt.strftime("%H:%M:%S")
    df = df.drop(['dateTime', 'closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol','takerBuyQuoteVol', 'ignore'], axis=1)
    column_names = ["date", "time", "open", "high", "low", "close", "volume"]
    df = df.reindex(columns=column_names)
    return df
    
api_key = ""
api_secret = ""
client = Client(api_key, api_secret)

fromDate = str(datetime.strptime('19/11/2021', '%d/%m/%Y'))
toDate = str(datetime.strptime('20/11/2021', '%d/%m/%Y'))
symbol = "BTCUSDT"
interval = Client.KLINE_INTERVAL_1MINUTE
df = GetHistoricalData(symbol, interval, fromDate, toDate)
df
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66295187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档