Write me a professionally looking Python 3.10 compatible script that's file is named "bnb1h.py".
"bnb1h.py" can help me download 1 hour kline BNBUSDT data from Binance historical spot data source for a specific date span.
Use API that doesn't need authentication.
Timestamp is converted to conventional standard in ms of dataframe.
Timestamp is the index.
Load from the API incrementally not larger than 1 week of data.
Each download request have a sleep time of a random seconds between 1000ms to 3000ms.
Show the downloading progress and their completion status of each of data requests and their pertaining information, such as the date and the sleep time before next iteration in one line in humanly readable and understandable format.
Combine all the dataframe together.
Only the columns of 'timestamp' and 'close' is needed.
Show me the header 5 row of the dataframe.
Show me the tail 5 row of the dataframe.
Output the dataframe to a csv file.
Make it into a script that take arguments in command line and the arguments are:
date start of the date span
output file name
Assume the end of the date span is today time of the system.
Be aware of that different objects can't be compared using the < operator.
Assistant
Sure, here's a Python 3.10 compatible script that meets your requirements:
python
import argparse
import pandas as pd
import requests
import time
import random
def download_data(start_time):
url = "https://api.binance.com/api/v3/klines"
end_time = int(time.time() * 1000)
delta_time = 604800000 # 1 week in ms
data_frames = []
while start_time < end_time:
params = {
"symbol": "BNBUSDT",
"interval": "1h",
"startTime": start_time,
"endTime": min(start_time + delta_time, end_time)
}
# Make request and handle errors
try:
response = requests.get(url, params=params)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return None
# Convert response to dataframe
df = pd.DataFrame(response.json(), columns=["timestamp", "open", "high", "low", "close", "volume", "close_time", "quote_asset_volume", "number_of_trades", "taker_buy_base_asset_volume", "taker_buy_quote_asset_volume", "ignore"])
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
df = df[["timestamp", "close"]]
df.set_index("timestamp", inplace=True)
# Add dataframe to list and update start_time
data_frames.append(df)
start_time += delta_time
# Sleep for random time between 1000ms and 3000ms
sleep_time = random.randint(1000, 3000) / 1000
print(f"Downloaded data until {df.index[-1]} - sleeping for {sleep_time:.2f} seconds")
time.sleep(sleep_time)
# Concatenate dataframes and return result
return pd.concat(data_frames)
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("start_date", help="Start date of date span (format: yyyy-mm-dd)")
parser.add_argument("output_file", help="Name of output CSV file")
args = parser.parse_args()
# Convert start_date to timestamp
start_time = int(pd.Timestamp(args.start_date).timestamp() * 1000)
# Download data and save to CSV
data = download_data(start_time)
if data is not None:
print("Download complete!")
data.to_csv(args.output_file)
# Show first and last 5 rows of dataframe
print("\nFirst 5 rows of dataframe:")
print(data.head())
print("\nLast 5 rows of dataframe:")
print(data.tail())
To run the script, open a terminal and navigate to the directory where the script is saved. Then type the following command:
css
python bnb1h.py yyyy-mm-dd output.csv
Replace "yyyy-mm-dd" with the start date of the date span you want to download, and replace "output.csv" with the name you want to give to the output file. The script will download the data and save it to a CSV file with the given name in the current directory. The first and last 5 rows of the dataframe will also be printed to the console.