Extracting Coin Data with Python and the Binance API
In this article, we will show you how to use the Binance API to extract data for specific coins in minute-by-minute increments. We will assume that you have basic knowledge of Python and the Binance API.
Prerequisites:
- You have a Binance API key with sufficient permissions.
- You have installed the
pybinance
library, which can be installed via pip:
pip install pybinance
Sample Code:
import pandas as pd
import pybinance
def get_coin_data(pair):
""""
Retrieve data for a specific coin pair.
Parameters:
pair(str): Coin pair (e.g. BCHUSDT-1m)
Returns:
pandas.DataFrame: A dataframe containing coin data in minute-by-minute increments
""""
api = pybinance.create_api(key='YOUR_API_KEY', secret='YOUR_API_SECRET')
candlestick_data = api.get_candlestick(pair, 'minute', interval='1m').data
Create a dataframe from the datadf = pd.DataFrame(candlestick_data)
return df
main definition() :
pairs = ['BCHUSDT-1m', 'BTCUSDT-1m']
List of coin pairs to extract data from
Initialize an empty list to store the retrieved dataframesdataframes = []
for a pair in pair:
try:
df = get_coin_data(pair)
dataframes.append(df)
except for an exception like e:
print(f"Error while retrieving data for {pair}: {e}")
Combine the extracted dataframes into a single csv fileoutput_df = pd.concat(dataframes)
output_df.to_csv('coin_data.csv', index=False)
if __name__ == '__main__':
main ()
Explanation:
- We define two functions:
get_coin_data
andmain
.
- In the
get_coin_data
function, we use the Binance API to retrieve minute-by-minute candlestick data for a specific coin pair.
- We create a dataframe from the extracted data using pandas.
- In the
main
function, we iterate through the list of coin pairs and callget_coin_data
for each pair. We append the resulting dataframe to an empty list calleddataframes
.
- Once all the pairs are processed, we combine the
dataframes
into a single dataframe using the pandasconcat
method.
- Finally, we save the combined dataframe to a csv file called
coin_data.csv
.
Example Use Case:
Suppose you want to extract historical coin data for BTCUSDT-1m and BCHUSDT-1m. You would like to:
- Run the script in your preferred Python environment.
- The script will download Binance’s minute-by-minute historical data for both pairs, storing it in a csv file called
coin_data.csv
.
- To analyze or visualize this data, you can use a pandas dataframe to filter and manipulate the data as needed.
Note: Remember to replace “YOUR_API_KEY” and “YOUR_API_SECRET” with your actual Binance API credentials.
Leave a Reply