還記得我們已經學會抓歷史價格、計算波動與夏普比率了嗎?今天換個角度,帶你看「市場全貌」:一次抓回前 10 大市值代幣的即時資訊(近即時),包含價格、24 小時/7 天/30 天的漲跌幅,並畫出市值排行榜。這樣的清單能幫助你快速定位:哪些代幣是市場資金的核心,近期氣氛偏多還是偏空。
pip install requests pandas matplotlib
import requests
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Heiti TC'
def fetch_top_tokens(vs_currency="usd", top_n=10):
url = "https://api.coingecko.com/api/v3/coins/markets"
params = {
"vs_currency": vs_currency, # 可改 'twd' 顯示新台幣
"order": "market_cap_desc", # 依市值排序
"per_page": top_n,
"page": 1,
"price_change_percentage": "24h,7d,30d"
}
headers = {"accept": "application/json", "user-agent": "fintech-ithome-30d"}
r = requests.get(url, params=params, headers=headers, timeout=20)
r.raise_for_status()
data = r.json()
cols = [
"id", "symbol", "name", "current_price", "market_cap",
"price_change_percentage_24h_in_currency",
"price_change_percentage_7d_in_currency",
"price_change_percentage_30d_in_currency"
]
df = pd.DataFrame([{k: item.get(k, None) for k in cols} for item in data])
df.rename(columns={
"id": "id",
"symbol": "代號",
"name": "名稱",
"current_price": f"價格({vs_currency.upper()})",
"market_cap": f"市值({vs_currency.upper()})",
"price_change_percentage_24h_in_currency": "24h(%)",
"price_change_percentage_7d_in_currency": "7d(%)",
"price_change_percentage_30d_in_currency": "30d(%)"
}, inplace=True)
# 整理小數與缺值
for col in ["24h(%)", "7d(%)", "30d(%)"]:
df[col] = pd.to_numeric(df[col], errors="coerce").fillna(0.0).round(2)
return df
# 抓取 Top10(USD)
df = fetch_top_tokens(vs_currency="usd", top_n=10)
# 顯示表格前幾列
print("=== 前 10 大市值代幣(USD)===")
print(df[["名稱", "代號", "價格(USD)", "24h(%)", "7d(%)", "30d(%)", "市值(USD)"]].head(10))
# 視覺化:畫市值前 10 長條圖(十億為單位)
plot_df = df.copy()
plot_df["市值(十億USD)"] = (plot_df["市值(USD)"] / 1e9).round(2)
plt.figure(figsize=(10, 6))
plt.barh(plot_df["名稱"], plot_df["市值(十億USD)"])
plt.gca().invert_yaxis() # 讓最大值在最上方
plt.title("加密代幣市值 Top 10(十億 USD)")
plt.xlabel("市值(十億 USD)")
plt.ylabel("代幣")
plt.grid(True, axis="x", alpha=0.3)
plt.tight_layout()
plt.show()
小提醒:若呼叫太頻繁,CoinGecko 可能暫時限流(429)。重試前先等幾秒;或把 top_n 調小一些。想切換幣別可改 vs_currency="twd" 直接用新台幣顯示。
今天你完成了第一個 DeFi 市場總覽小工具:免金鑰、資料乾淨、一步到位。
明天(Day14)我們會在此基礎上做一個 「自選代幣追蹤表」:輸入代幣清單,一鍵輸出報價與漲跌,順手加上一個「波動提醒」欄位(例如 24h 超過 ±8% 亮燈),讓你更貼近實戰的監控節奏。
風險聲明:本文僅供學習示範,非投資建議。加密資產波動高,請留意資金與風險管理。