-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi
More file actions
42 lines (32 loc) · 1.63 KB
/
Copy pathapi
File metadata and controls
42 lines (32 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from binance.client import Client
import pandas as pd
import datetime
# API密钥和私钥
API_KEY = '你的API_KEY'
API_SECRET = '你的API_SECRET'
# 初始化Binance客户端
client = Client(API_KEY, API_SECRET)
# 获取BTC/USDT的历史K线数据
def get_btc_ohlcv(symbol='BTCUSDT', interval='1d', start_date=None, end_date=None, limit=1000):
# 设置开始和结束时间
if start_date is None:
start_date = "1 Jan, 2017" # 默认从2017年1月1日开始
if end_date is None:
end_date = datetime.datetime.now().strftime("%d %b, %Y") # 默认到当前日期
# 获取历史数据
klines = client.get_historical_klines(symbol, interval, start_date, end_date, limit=limit)
# 转换为Pandas DataFrame格式
ohlcv_data = pd.DataFrame(klines, 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'])
# 转换时间戳为日期格式
ohlcv_data['timestamp'] = pd.to_datetime(ohlcv_data['timestamp'], unit='ms')
# 选择需要的列
ohlcv_data = ohlcv_data[['timestamp', 'open', 'high', 'low', 'close', 'volume']]
# 设置时间戳为索引
ohlcv_data.set_index('timestamp', inplace=True)
return ohlcv_data
# 示例:获取BTC的1小时历史数据(每小时1根K线)
btc_data = get_btc_ohlcv(symbol='BTCUSDT', interval='1h', start_date='1 Jan, 2023', end_date='1 Jan, 2024')
print(btc_data.head())