import ccxt
import pandas as pd
import matplotlib.pyplot as plt
def fetch_crypto_data(symbol="BTC/USDT", timeframe="1h", limit=500, plot=True):
"""
從 Binance 抓取加密貨幣歷史 K 線資料 (OHLCV),並可選擇畫圖
參數:
symbol (str): 交易對,例如 "BTC/USDT"
timeframe (str): 時間週期,例如 "1m", "5m", "1h", "1d"
limit (int): 抓取的筆數 (最多1000)
plot (bool): 是否自動畫收盤價走勢圖
回傳:
pandas.DataFrame: 包含 timestamp, open, high, low, close, volume
"""
# 建立 Binance 交易所物件
exchange = ccxt.binance()
# 抓取歷史資料
ohlcv = exchange.fetch_ohlcv(symbol, timeframe=timeframe, limit=limit)
# 轉換成 DataFrame
df = pd.DataFrame(ohlcv, columns=['timestamp','open','high','low','close','volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
# 畫收盤價走勢圖
if plot:
plt.figure(figsize=(12,5))
plt.plot(df['timestamp'], df['close'], label=f"{symbol} Close Price")
plt.title(f"{symbol} ({timeframe}) 收盤價走勢圖")
plt.xlabel("時間")
plt.ylabel("價格 (USDT)")
plt.legend()
plt.grid(True)
plt.show()
return df
# 測試:抓 BTC/USDT 1小時線,最近 200 筆
if __name__ == "__main__":
df = fetch_crypto_data("BTC/USDT", "1h", 200, plot=True)
print(df.tail())