Getting Data with Binance API
Binance API provides free historical financial data. There are multiple ways to get data from Binance API. The first way requires keys which can be obtained by Binance members.
First import these libraries, enter your api keys and define requiered parameters. (use pip install python-binance for binance library)
import pandas as pd
import matplotlib.pyplot as plt
from binance.client import Client
binance_api_key = ''
binance_api_secret = ''
binsizes = {"1m": 1, "5m": 5, "1h": 60, "1d": 1440}
binance_client = Client(api_key=binance_api_key, api_secret=binance_api_secret)
Define a function that returns historical data in pandas dataframe format.
def get_data_from_binance(symbol, period, StartDate, EndDate):
klines = binance_client.get_historical_klines(symbol, period, StartDate, EndDate)
data = pd.DataFrame(klines, columns = ['timestamp'+symbol, 'open', 'high', 'low', ''+symbol, 'volume', 'close_time', 'quote_av', 'trades', 'tb_base_av', 'tb_quote_av', 'ignore' ])
data['timestamp'+symbol] = pd.to_datetime(data['timestamp'+symbol], unit='ms')
data.set_index('timestamp'+symbol, inplace=True)
return data
Second method requires no api key. First import required libraries:
import pandas as pd
import json
import requests
import datetime as dt
Define a function that returns selected symbol's historical data in a dataframe:
def get_data(symbol, interval, limit):
root_url = 'https://api.binance.com/api/v3/klines'
url = root_url + '?symbol=' + symbol + '&interval=' + interval + '&limit=' + limit
data = json.loads(requests.get(url).text)
df = pd.DataFrame(data)
df.columns = ['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Qutoe asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore']
df.index = [dt.datetime.fromtimestamp(x/1000.0) for x in df['Open time']]
return df
An example usage of this function:
daily_btc = get_data('BTCUSDT', '1d', '1000')
Finally, for both methods you can save the closing prices to a csv to use later:
close_df = df[['Close']].astype(float)
close_df.to_csv('historical-prices.csv', index=True, index_label='date')