返回 Expert 笔记
Expert Day 73

永续合约定价 — Funding Rate 与 Cash-and-Carry

Perpetual swap 机制、Funding rate 公式、Basis 与 Cash-and-Carry、跨交易所 funding 套利

2026-07-13
Phase 2 - 量化数学与衍生品定价 (Day 61-74)
量化永续合约FundingRateBasis套利

日期: 2026-07-13 方向: 量化 / 衍生品定价 阶段: Phase 2 - 量化数学与衍生品定价 (Day 61-74) 标签: #量化 #永续合约 #FundingRate #Basis #套利


今日目标

类型内容
学习Perpetual swap 机制、Funding rate 公式、Basis 与 Cash-and-Carry、跨交易所 funding 套利
实操抓 Binance / Bybit / OKX funding rate,实现 funding rate 计算与套利分析
产出funding.py — funding rate 工具 + 套利识别

一、永续合约基础

1.1 定义

永续合约 (Perpetual Swap):无到期日的期货。BitMEX 2016 年首创,现在是加密最活跃产品(Binance Perp 日交易量 $200B+)。

与传统期货对比

维度传统期货永续合约
到期日
价格锚定自然到期收敛Funding rate
Roll必须不需要
Leverage中等高(10-100x)

1.2 Funding Rate 机制

每隔 funding interval(通常 8h 或 1h),long 和 short 之间互相支付:

$$ \text{Funding Payment} = \text{Position Notional} \times \text{Funding Rate} $$

Funding Rate 由两部分组成:

$$ \text{Funding Rate} = \text{Premium Index} + \text{Clamp}(\text{Interest Rate} - \text{Premium}, \pm \text{cap}) $$

Premium Index

$$ \text{Premium} = \frac{\text{Mark Price} - \text{Index Price}}{\text{Index Price}} $$

Binance 公式(实际示例):

$$ F = P + \text{Clamp}(I - P, \pm 0.05%) $$

$P$ 是 premium,$I$ 是 interest rate (usually 0.01%/8h = 0.03%/day)。

1.3 Funding Direction

PremiumFunding Rate谁付谁
Mark > Index (long demand >)PositiveLong → Short
Mark < Index (short demand >)NegativeShort → Long

经济直觉:market 参与者 long 太多 → mark 高于 spot → 让 long 付 funding 平衡需求。

1.4 No-Arbitrage Pricing

理想情况下,永续合约 mark price 应等于 fair value:

$$ \text{Fair} = \text{Spot} \cdot (1 + r \cdot \Delta t) - \text{Funding accrued} $$

或连续:

$$ F_{\text{fair}}(t) = S_t \cdot e^{(r - q_{\text{lend}})(T - t)} $$

Long perp ≈ long spot + 收 funding。理论 funding ≈ $r - q_{\text{lend}}$。

1.5 Basis

Basis $= F - S$,即 perp price - spot。对永续:

$$ \text{Basis} = S \cdot (\text{Funding rate, annualized} \cdot t) $$

加密市场 perp basis 经常显著(大牛市 +20% 年化 funding)。


二、Cash-and-Carry 套利

2.1 经典套利

发现 funding rate > 借款利率时:

  1. Long Spot: 买 1 BTC(用 USDC,利率 5%/年)
  2. Short Perp: 空 1 BTC perp(收 funding)
  3. Lock-in: funding rate - 5%/年 = 锁定利差

例:BTC funding 30%/年化,借款 5%/年 → 锁定 25%/年 套利。

风险

  • Funding rate 突变
  • Liquidation(虽然 hedged,但 perp side 可能因 mark price 暴动 trigger 清算)
  • Spread 成本(开仓/平仓滑点)
  • Counter-party risk(CEX 黑天鹅)

2.2 跨交易所 Funding Arb

不同交易所同时段 funding 不同:

  • Binance BTC perp: +20%/year
  • OKX BTC perp: +28%/year

策略:long Binance perp + short OKX perp = 净收 8%/year(但有 basis convergence risk)。

2.3 Funding Direction Arb

当 funding 持续高且收敛时(mark > index 但收敛),可以:

  • Short perp 收 funding
  • Hedge with spot long

更复杂的:long volatility(funding 随 vol 变动)。

2.4 Funding Carry vs Stat Arb

策略风险年化收益
Pure cash-and-carryLow (basis risk)5-30%
Cross-exchange funding arbMedium3-10%
Funding direction predictionHigh20-50%

机构(GSR、Jump)通常 mix:cash-carry 作 base,funding pred 作 alpha。


三、数学模型

3.1 Premium 演化

设 $P_t$ 是 premium,OU 过程模拟均值回复:

$$ dP_t = -\kappa (P_t - 0) dt + \sigma_P dW_t $$

$\kappa$ 大 → premium 快速回归 0;加密市场 $\kappa \approx 5$(半衰期 ~3.5h)。

3.2 Funding Predicted Value

未来 funding 的现值:

$$ \text{Future Funding NPV} = \int_0^T F_t e^{-rt} dt $$

期望:

$$ \mathbb{E}\left[\int_0^T F_t dt\right] = T \cdot \bar{F} $$

其中 $\bar{F}$ 是长期均值(约 $r_{\text{spread}}$)。

3.3 Funding Volatility

Funding rate 本身波动:BTC 8h funding std ≈ 0.05%。年化 std ≈ $0.0005 \cdot \sqrt{365 \cdot 3} \approx 1.65%$。

3.4 Cap and Floor

大多交易所 funding rate 有上下限:

  • Binance: ±0.5% per 8h (即 ±54.75% per year)
  • Bybit: ±0.075% per 8h
  • OKX: ±0.375% per 4h

突破 cap 时 trader 可"钉死"在 cap 上获利(如果保证金允许)。


四、代码实现

"""
funding.py - 永续合约 funding rate 计算与套利分析
依赖: requests, pandas, numpy
"""

import requests
import pandas as pd
import numpy as np
from datetime import datetime, timezone


# ====== 1. 数据抓取 ======

def fetch_binance_funding(symbol="BTCUSDT", limit=500):
    """Binance USD-M funding rate history"""
    url = "https://fapi.binance.com/fapi/v1/fundingRate"
    params = {"symbol": symbol, "limit": limit}
    r = requests.get(url, params=params, timeout=10)
    r.raise_for_status()
    data = r.json()
    df = pd.DataFrame(data)
    df["fundingTime"] = pd.to_datetime(df["fundingTime"], unit="ms")
    df["fundingRate"] = df["fundingRate"].astype(float)
    return df


def fetch_binance_premium_index(symbol="BTCUSDT"):
    """Binance premium index (current)"""
    url = "https://fapi.binance.com/fapi/v1/premiumIndex"
    params = {"symbol": symbol}
    r = requests.get(url, params=params, timeout=10)
    return r.json()


def fetch_bybit_funding(symbol="BTCUSDT", limit=200):
    """Bybit perpetual funding rate"""
    url = "https://api.bybit.com/v5/market/funding/history"
    params = {"category": "linear", "symbol": symbol, "limit": limit}
    r = requests.get(url, params=params, timeout=10)
    data = r.json().get("result", {}).get("list", [])
    df = pd.DataFrame(data)
    if len(df) == 0:
        return df
    df["fundingRateTimestamp"] = pd.to_datetime(df["fundingRateTimestamp"], unit="ms")
    df["fundingRate"] = df["fundingRate"].astype(float)
    return df


def fetch_okx_funding(symbol="BTC-USDT-SWAP"):
    """OKX swap funding rate (current)"""
    url = "https://www.okx.com/api/v5/public/funding-rate"
    params = {"instId": symbol}
    r = requests.get(url, params=params, timeout=10)
    return r.json()


# ====== 2. Funding 计算工具 ======

def annualize_funding(rate_per_period, periods_per_day=3):
    """8h funding -> annualized"""
    return rate_per_period * periods_per_day * 365


def funding_pnl(notional_usd, funding_rate_per_period, n_periods, side="long"):
    """
    side='long': long pays funding when rate > 0
    side='short': short receives funding when rate > 0
    """
    sign = -1 if side == "long" else 1
    return sign * notional_usd * funding_rate_per_period * n_periods


# ====== 3. Cash-and-Carry 套利分析 ======

def cash_carry_pnl(notional_usd, funding_apy, borrow_apy, days, fees_pct=0.001):
    """
    Cash-and-Carry: long spot + short perp
    收 funding (perp), 付 borrow rate (USD)
    """
    funding_recv = notional_usd * funding_apy * days / 365
    borrow_cost = notional_usd * borrow_apy * days / 365
    fees = notional_usd * fees_pct * 2  # 开仓+平仓
    return funding_recv - borrow_cost - fees


# ====== 4. 跨交易所 funding spread 监控 ======

def cross_exchange_spread(symbol="BTCUSDT"):
    """对比 Binance / Bybit / OKX 当前 funding rate"""
    rates = {}
    try:
        bn = fetch_binance_premium_index(symbol)
        rates["Binance"] = float(bn["lastFundingRate"])
    except Exception:
        rates["Binance"] = None

    try:
        bb = fetch_bybit_funding(symbol, 1)
        if len(bb) > 0:
            rates["Bybit"] = float(bb.iloc[0]["fundingRate"])
    except Exception:
        rates["Bybit"] = None

    try:
        ok = fetch_okx_funding(symbol.replace("USDT", "-USDT-SWAP"))
        if "data" in ok and len(ok["data"]) > 0:
            rates["OKX"] = float(ok["data"][0]["fundingRate"])
    except Exception:
        rates["OKX"] = None

    return rates


# ====== 5. Funding rate stats ======

def funding_stats(df, periods_per_day=3):
    """Funding rate 历史统计"""
    if len(df) == 0:
        return {}
    rates = df["fundingRate"].values
    return {
        "mean": np.mean(rates),
        "std": np.std(rates),
        "min": np.min(rates),
        "max": np.max(rates),
        "annualized_mean": np.mean(rates) * periods_per_day * 365,
        "annualized_std": np.std(rates) * np.sqrt(periods_per_day * 365),
        "skew": ((rates - rates.mean())**3).mean() / rates.std()**3,
        "n": len(rates),
    }


# ====== 6. 主流程 ======

def main():
    print("=" * 70)
    print("永续合约 Funding Rate 分析")
    print(f"  时间: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 70)

    # Binance BTC funding 历史
    print("\n[1] Binance BTC-USDT Perp Funding History (8h intervals):")
    bn_df = fetch_binance_funding("BTCUSDT", 500)
    if len(bn_df) > 0:
        stats = funding_stats(bn_df)
        print(f"  最近 {stats['n']} periods (~{stats['n']/3:.1f} days):")
        print(f"    平均:        {stats['mean']*100:+.4f}% per 8h")
        print(f"    年化平均:    {stats['annualized_mean']*100:+.2f}%")
        print(f"    标准差:      {stats['std']*100:.4f}%")
        print(f"    年化波动:    {stats['annualized_std']*100:.2f}%")
        print(f"    最大:        {stats['max']*100:+.4f}%")
        print(f"    最小:        {stats['min']*100:+.4f}%")
        print(f"    Skewness:    {stats['skew']:+.3f}")

    # 跨交易所 spread
    print("\n[2] 当前 Funding Rate 跨交易所对比 (BTC):")
    rates = cross_exchange_spread("BTCUSDT")
    print(f"  {'Exchange':<12} {'Funding (per period)':<22} {'Annualized':>12}")
    period_per_day = {"Binance": 3, "Bybit": 3, "OKX": 6}
    for ex, r in rates.items():
        if r is None:
            print(f"  {ex:<12} N/A")
            continue
        ann = r * period_per_day[ex] * 365
        print(f"  {ex:<12} {r*100:+.5f}%               {ann*100:+.2f}%")

    if all(rates.values()):
        # Spread
        spreads = {
            "Binance - Bybit": rates["Binance"] - rates["Bybit"],
            "Binance - OKX (per 8h equivalent)": rates["Binance"] - rates["OKX"]*4/3,
        }
        print("\n  Spreads:")
        for k, v in spreads.items():
            print(f"    {k:<32} {v*100:+.5f}% per period")

    # Cash-and-Carry 模拟
    print("\n[3] Cash-and-Carry 模拟 ($100K, 30 days)")
    print(f"  {'Funding APY':>12} {'Borrow APY':>12} {'Net P&L':>12}")
    if rates.get("Binance"):
        funding_apy = annualize_funding(rates["Binance"], 3)
        for borrow in [0.05, 0.08, 0.10]:
            pnl = cash_carry_pnl(100000, funding_apy, borrow, 30, fees_pct=0.001)
            print(f"  {funding_apy*100:>11.2f}% {borrow*100:>11.2f}% ${pnl:>10.2f}")

    # Funding rate 极值与套利机会
    print("\n[4] 历史 Funding 极值时段 (Binance BTC):")
    if len(bn_df) > 0:
        extreme = bn_df[abs(bn_df["fundingRate"]) > 0.005].sort_values("fundingRate", ascending=False)
        print(f"  Top 5 极值 funding (|F| > 0.5% per 8h):")
        for _, row in extreme.head(5).iterrows():
            ann = row["fundingRate"] * 3 * 365 * 100
            print(f"    {row['fundingTime'].strftime('%Y-%m-%d %H:%M')}: "
                  f"{row['fundingRate']*100:+.4f}% per 8h ({ann:+.2f}% APY)")

    # ETH 对比
    print("\n[5] ETH-USDT Perp Funding (recent):")
    eth_df = fetch_binance_funding("ETHUSDT", 100)
    if len(eth_df) > 0:
        eth_stats = funding_stats(eth_df)
        print(f"  ETH 年化均值: {eth_stats['annualized_mean']*100:+.2f}%")
        print(f"  ETH vs BTC funding 相关性 (近 100 periods):")
        if len(bn_df) >= 100:
            common_n = min(len(eth_df), 100)
            corr = np.corrcoef(
                bn_df["fundingRate"].values[-common_n:],
                eth_df["fundingRate"].values[-common_n:]
            )[0, 1]
            print(f"    corr = {corr:+.4f}")


if __name__ == "__main__":
    main()

预期输出

[1] Binance BTC-USDT Perp Funding History (8h intervals):
  最近 500 periods (~166.7 days):
    平均:        +0.0089% per 8h
    年化平均:    +9.74%
    标准差:      0.0421%
    年化波动:    13.96%
    最大:        +0.3000%
    最小:        -0.0823%
    Skewness:    +1.832

[2] 当前 Funding Rate 跨交易所对比 (BTC):
  Exchange     Funding (per period)   Annualized
  Binance      +0.00892%              +9.77%
  Bybit        +0.00854%              +9.35%
  OKX          +0.00510%              +11.17%

  Spreads:
    Binance - Bybit                   +0.00038% per period

五、真实数据/案例

BTC Funding 历史 Regime

周期平均 funding APY状态
2020 牛市+25-50%极度看涨
2022 熊市-5 to +5%震荡
2023 复苏+10-20%温和看涨
2024 ETF+30-60%大牛市
2025-2026 平稳+5-15%平衡

极端 Funding Event

2024-03-08 BTC 突破 $70K:Binance funding rate 触顶 +0.3% per 8h(约 +330% APY)持续多个 8h 周期。

  • Cash-and-carry 一周回报: ~6% 净
  • 风险事件:3-9 BTC 跌 -8%,short perp 一些被强平

跨交易所套利实例

2025-Q3 Bybit funding > Binance 8 个 8h 周期。机构策略:

  • Long Binance perp + Short Bybit perp
  • 锁定差额 ~5%/year
  • 限制:collateral fragmented across exchanges

六、加密市场特化

6.1 Funding 频率差异

交易所Funding 频率年化 cap
Binance8h (3x/day)±54.75%
Bybit8h±82%
OKX4h or 8hdepends on contract
dYdX1h (24x/day)flexible
GMX (DeFi)1h or per-blocknone

频率高意味着 funding 更精细但 retail 难追踪。

6.2 DeFi vs CEX Funding

GMX V2 funding 由"borrow rate"和"funding rate"分别控制:

  • Borrow rate: 与 utilization 相关
  • Funding rate: long-short imbalance

与 CEX 区别:DeFi funding 通常更平滑(less spike),但 base level 高(incentive 加成)。

6.3 Stable Pair 反向

USDT-USDC perp 等"稳定对"的 funding 通常 ≈ 0。但 depeg 事件(如 SVB 2023)瞬间 funding 飙到 ±5% per 8h。

6.4 Token Pre-launch Perps

Aevo / Hyperliquid 提供 pre-launch token perpetual。Funding 极不稳定(无 spot 锚),有时 ±30% per 8h。这是赌博而非套利


七、常见陷阱

  1. Funding direction 搞反:positive funding 是 long pay short,不是 short pay long。

  2. Annualization 用错:Binance 8h × 3 × 365;OKX 8h × 3 × 365 同;dYdX 1h × 24 × 365。混了导致估算偏 8x。

  3. Funding 相关 fees:成交 fees + funding fees 双收,开仓滑点不算 funding。

  4. Liquidation 风险被低估:cash-and-carry 看似 hedge,但 perp side 可能在 mark price 暴动时单边清算。

  5. Funding rate cap 撞顶:极端市场 cap = 0.5% per 8h,但实际市场需要 1%。market 会在 cap 处"卡住",此时机会很大但执行难。

  6. Cross-margin 下连环清算:spot leg 在 CEX 1 上,perp leg 在 CEX 2 上。一边清算另一边裸 exposure。


八、关键速查

公式表达式
Premium$(P_{\text{mark}} - P_{\text{index}}) / P_{\text{index}}$
Funding (Binance-style)$\text{Premium} + \text{Clamp}(I - P, \pm 0.05%)$
Annualize 8h funding$f \times 3 \times 365$
Cash-and-carry P&L$N (\text{funding} - r) \cdot t/365 - \text{fees}$
Fair perp price$S e^{(r-q_{\text{lend}})t}$
Endpoint用途
fapi.binance.com/fapi/v1/fundingRateBinance funding history
fapi.binance.com/fapi/v1/premiumIndexPremium index (current)
api.bybit.com/v5/market/funding/historyBybit funding
okx.com/api/v5/public/funding-rateOKX current funding

九、面试题

Q1: 解释 Binance BTC perp 当前 funding rate 0.01%/8h 是什么意思?年化是多少?谁付谁?

0.01%/8h × 3 × 365 = +10.95% annualized。Positive funding 表示 long demand > short demand,所以 long 付 short 0.01% per 8h。

Q2: Cash-and-carry arbitrage 在 funding rate +30%/year 时具体怎么做?

(1) Long spot BTC(用 USD 借款,5%);(2) Short perp BTC(收 funding +30%);(3) Net 收 25%/year,前提是 funding 维持。需要 (a) margin 双边充足;(b) hedge 完美(spot vs perp 数量一致);(c) 监控 funding 突变。

Q3: 为什么加密 funding rate 平均为正?

(1) Long bias:散户多 long,少 short;(2) Lending demand:BTC 借出收益 < USD lending;(3) Risk premium:long position 承担 BTC 下行风险,需要 incentive。

Q4: 跨交易所 funding 套利的最大风险是什么?

Counterparty 风险(一个交易所黑天鹅)+ basis convergence(spread 可能扩大而非收敛)+ collateral fragmentation(margin 分散无法相互调拨)。FTX 2022 是惨例。

Q5: GMX V2 的 funding 与 Binance funding 有什么区别?

(1) GMX 由 LP 池作对手方,funding 流向 LP 而非交易者间;(2) GMX 加 borrow fee(与 utilization 挂钩);(3) DeFi funding 计算更频繁(1h or per-block),更平滑但 base 高 5-10%。


十、明日预告

Day 74: Week 11 复习 — 衍生品定价整合,写"DeFi 期权产品分析"报告。明天我们汇总 Day 61-73 的所有知识,做一个完整的产品深度分析——选择一个 DeFi 期权协议,从数学定价、协议机制、LP 经济到面试要点全方位剖析。