私は個人開発者として、暗号資産クオンツの補助システムを2025年から運用しています。レバレッジ取引において、OKXの資金調達率(Funding Rate)は市場の過熱感を示す最重要指標です。本記事では、OKXのパブリックAPIから過去の資金調達率を取得し、pandasで異常値をクリーニングした上で、HolySheep AIのLLMで市場コメントを自動生成する一連のデータパイプラインを実装例つきで解説します。

なぜ資金調達率を分析するのか

資金調達率とは、無期限先物(パーペチュアル)におけるロング・ショート間の資金移動を示す金利で、通常は8時間ごとに発生します。+0.01%以上が続けば「ロング過熱」、-0.01%以下が続けば「ショート過熱」と判断されます。個人開発者の私の場合、深夜帯のセンチメント変化を自動で察知したいと思い、本パイプラインを自作しました。

全体の処理フロー

  1. OKXパブリックAPIから資金調達率履歴を取得(/api/v5/public/funding-rate-history
  2. pandas DataFrameに変換し、タイムゾーンをUTC→JSTに統一
  3. IQR法とZ-scoreで異常値を検出・除外
  4. HolySheep AIのLLMで日本語の市場サマリーを生成

Step 1: OKX APIからのデータ取得

import time
import requests
import pandas as pd

OKX_BASE = "https://www.okx.com"
SYMBOL = "BTC-USDT-SWAP"

def fetch_funding_history(symbol: str, after_ms: int = None, limit: int = 100):
    params = {"instId": symbol, "limit": str(limit)}
    if after_ms:
        params["after"] = str(after_ms)
    r = requests.get(
        f"{OKX_BASE}/api/v5/public/funding-rate-history",
        params=params, timeout=10
    )
    r.raise_for_status()
    data = r.json()
    if data.get("code") != "0":
        raise RuntimeError(f"OKX API error: {data}")
    return data["data"]

def fetch_all_history(symbol: str, page_size: int = 100):
    rows, cursor = [], None
    while True:
        batch = fetch_funding_history(symbol, after_ms=cursor, limit=page_size)
        if not batch:
            break
        rows.extend(batch)
        cursor = int(batch[-1]["fundingTime"]) - 1
        if len(batch) < page_size:
            break
        time.sleep(0.05)  # レート制限回避(20回/2秒)
    return rows

records = fetch_all_history(SYMBOL)
df = pd.DataFrame(records, columns=["fundingTime", "instId", "fundingRate", "realizedRate"])
df["fundingTime"] = pd.to_datetime(df["fundingTime"].astype(int), unit="ms", utc=True)
df["fundingRate"] = df["fundingRate"].astype(float)
df = df.sort_values("fundingTime").reset_index(drop=True)
df["jst"] = df["fundingTime"].dt.tz_convert("Asia/Tokyo")
print