DeFi 協議數學模型完整指南:AMM 曲線、利率模型與清算機制的量化分析

本文從量化金融視角深入分析 DeFi 領域最具代表性的數學模型,包括自動做市商(AMM)的定價曲線、借貸協議的利率模型、以及清算機制的量化實現。提供完整的數學推導、Python/JavaScript 程式碼範例、以及實際市場數據驗證。

DeFi 協議數學模型完整指南:AMM 曲線、利率模型與清算機制的量化分析

概述

去中心化金融(DeFi)協議的核心價值建立在精密的數學模型之上。這些模型決定了流動性效率、風險分配、以及協議的長期可持續性。本文從量化金融視角出發,深入分析 DeFi 領域最具代表性的數學模型,包括自動做市商(AMM)的定價曲線、借貸協議的利率模型、以及清算機制的量化實現。我們將提供完整的數學推導、程式碼範例、以及實際市場數據驗證。

截至 2026 年第一季度,以太坊 DeFi 生態系統的總鎖定價值(TVL)超過 1,000 億美元,涵蓋借貸、交易、保險、衍生品等多個垂直領域。理解這些協議的數學基礎對於開發者、量化交易者、風險管理人員都至關重要。

第一章:自動做市商(AMM)數學模型

1.1 恆定乘積模型(Constant Product Model)

恆定乘積模型是 Uniswap V2 採用的核心演算法,也是最廣泛使用的 AMM 形式。

基本公式推導

給定兩個代幣池的初始數量 $x$ 和 $y$,以及交易費用率 $\gamma$,模型確保:

$$(x + \Delta x) \cdot (y - \Delta y) = k \cdot (1 - \gamma)$$

其中:

無費用交易推導

當 $\gamma = 0$ 時(僅用於數學推導):

無費用情況下的交易分析:

初始狀態:(x₀, y₀)
交易後狀態:(x₀ + Δx, y₀ - Δy)

根據守恆條件:
(x₀ + Δx) × (y₀ - Δy) = x₀ × y₀

展開:
x₀y₀ - x₀Δy + y₀Δx - ΔxΔy = x₀y₀

簡化:
-y₀Δy + y₀Δx = ΔxΔy

當 Δx 和 Δy 很小時,ΔxΔy 可忽略:
-y₀Δy + y₀Δx ≈ 0
Δy ≈ (y₀/x₀)Δx

因此無費用交易的價格:
P = Δy/Δx ≈ y₀/x₀

帶費用交易推導

有費用情況下的精確分析:

設費用為 f = Δx × γ
實際進入池子的 Δx' = Δx - f = Δx(1 - γ)

新的守恆條件:
(x + Δx(1 - γ)) × (y - Δy) = k

解出 Δy:
Δy = y - k / (x + Δx(1 - γ))

代入 k = xy:
Δy = y - xy / (x + Δx(1 - γ))
Δy = y(1 - x / (x + Δx(1 - γ)))
Δy = y × (Δx(1 - γ)) / (x + Δx(1 - γ))

最終公式:
Δy = (y × Δx × (1 - γ)) / (x + Δx × (1 - γ))

滑點計算

滑點是衡量 AMM 交易效率的關鍵指標:

def calculate_swap_output(x_pool, y_pool, dx, fee_rate=0.003):
    """
    計算交易輸出和滑點
    
    參數:
    - x_pool: 代幣 X 的池子數量
    - y_pool: 代幣 Y 的池子數量
    - dx: 輸入的代幣 X 數量
    - fee_rate: 交易費用率
    
    返回:
    - dy: 輸出的代幣 Y 數量
    - slippage: 滑點百分比
    """
    # 扣除費用
    dx_after_fee = dx * (1 - fee_rate)
    
    # 計算輸出
    dy = (y_pool * dx_after_fee) / (x_pool + dx_after_fee)
    
    # 計算無費用時的理論輸出
    dy_no_fee = y_pool * dx / x_pool
    
    # 計算滑點
    slippage = (dy_no_fee - dy) / dy_no_fee * 100
    
    return dy, slippage

# 數值示例
x_pool = 1_000_000  # 100萬 USDC
y_pool = 300         # 300 ETH
dx = 10_000          # 交換 10,000 USDC

dy, slippage = calculate_swap_output(x_pool, y_pool, dx)
print(f"輸出 ETH: {dy:.6f}")
print(f"滑點: {slippage:.2f}%")
# 輸出: 2.941176 ETH, 滑點: 0.99%

1.2 穩定幣交換模型(StableSwap)

Curve Finance 採用了針對穩定幣優化的 StableSwap 模型,其核心思想是在常數和與常數積之間平滑過渡。

數學推導

StableSwap 的核心公式為:

$$D = An^n \sum xi + D \cdot \frac{A n^n \sum xi}{D^{n-1}} + \frac{D^{n+1}}{A n^{2n} \prod x_i}$$

簡化為雙代幣形式:

$$K{swap} = \frac{D^n}{n^n \prod xi}$$

線性與雙曲線的混合

def stableswap_dy(x, y, A, n=2, D=None):
    """
    StableSwap 價格計算
    
    參數:
    - x, y: 兩個代幣池的數量
    - A: 放大係數(Amplification Factor)
    - n: 代幣種類數
    - D: 不變量
    
    返回:
    - dy: 輸出數量
    """
    if D is None:
        # 計算 D(不變量)
        D = stableswap_get_D(x, y, A, n)
    
    # 計算 Ann = A * n^n
    Ann = A * n ** n
    
    # 中間計算
    xjs = [x, y]
    ys = D * D / (n ** 2 * x * y)
    
    # 使用牛頓法計算輸出
    for _ in range(10):
        y_prev = ys
        
        # 計算 S = sum(x_i)
        S = x + ys
        
        # 使用牛頓法迭代
        k = Ann * S * y_prev
        k = k * y_prev
        d = (Ann - 1) * S * S + D * D + Ann * S * y_prev + k / y_prev
        
        ys = y_prev - (D * y_prev * y_prev + k) / d
        
        if abs(ys - y_prev) < 1:
            break
    
    dy = x - ys
    
    return dy

def stableswap_get_D(x, y, A, n=2):
    """計算 StableSwap 不變量 D"""
    S = x + y
    D = S
    
    for _ in range(20):
        D_P = D * D / (n ** 2 * x * y)
        D = (2 * D + D_P) * S / (3 * A)
        
        if abs(D - D_P) < 1:
            break
    
    return D

放大係數 A 的影響

放大係數 A 對曲線形狀的影響:

A 較低時(如 A=100):
- 曲線更接近常數乘積
- 適合波動性資產
- 流動性分散

A 較高時(如 A=1000):
- 曲線更接近常數和
- 更適合穩定幣交易
- 流動性集中在中間價格

數值比較(假設 x=y=1,000,000):
| A     | 滑點(1% 交易)| 流動性效率 |
|-------|----------------|-----------|
| 50    | 0.82%         | 低        |
| 200   | 0.45%         | 中        |
| 1000  | 0.08%         | 高        |
| 5000  | 0.015%        | 極高      |

1.3 集中流動性模型(Uniswap V3)

Uniswap V3 引入的集中流動性是 AMM 演算法的重大創新,允許流動性提供者將資金集中在特定價格範圍。

流動性量子化

class ConcentratedLiquidity:
    def __init__(self, sqrt_price, liquidity):
        self.sqrt_price = sqrt_price
        self.liquidity = liquidity
    
    @staticmethod
    def calc_token_amounts(liquidity, sqrt_price_lower, sqrt_price_upper, is_token0):
        """
        計算在特定流動性區間內的代幣數量
        """
        # 價格範圍
        price_lower = sqrt_price_lower ** 2
        price_upper = sqrt_price_upper ** 2
        price_current = liquidity.sqrt_price ** 2
        
        if is_token0:
            # Token0 數量計算
            amount0 = liquidity.liquidity * (
                1 / sqrt_price_lower - 1 / sqrt_price_upper
            )
            # Token1 數量計算
            amount1 = liquidity.liquidity * (
                sqrt_price_upper - sqrt_price_lower
            )
        else:
            amount0 = liquidity.liquidity * (
                sqrt_price_upper - sqrt_price_lower
            )
            amount1 = liquidity.liquidity * (
                1 / sqrt_price_lower - 1 / sqrt_price_upper
            )
        
        return amount0, amount1
    
    @staticmethod
    def calc_liquidity_from_amounts(
        amount0, amount1, 
        sqrt_price_lower, sqrt_price_upper
    ):
        """
        根據代幣數量計算所需流動性
        """
        # 計算 x 和 y
        x = amount0
        y = amount1
        
        # 計算 ΔS = √P_upper - √P_lower
        delta_s = sqrt_price_upper - sqrt_price_lower
        
        # 計算 Δ(1/√P)
        delta_inv_price = 1 / sqrt_price_lower - 1 / sqrt_price_upper
        
        # 流動性公式
        liquidity0 = x / delta_inv_price
        liquidity1 = y / delta_s
        
        return min(liquidity0, liquidity1)

範圍訂單(Range Orders)

Uniswap V3 允許建立「範圍訂單」,類似於傳統交易所的限價單:

範圍訂單數學模型:

假設流動性集中在 [P_lower, P_upper] 區間

當 P ∈ [P_lower, P_upper] 時:
- 交易者獲得 token1
- 流動性提供者存入 token0
- 隨著 P 上升,逐漸轉換為 token1

當 P 離開區間時:
- 流動性完全轉換為單一代幣
- 需要手動調整範圍或移除流動性

收益計算:
Price(t) ∈ [P_lower, P_upper] 時
Amount_out = Initial_token0 × (P(t) / P_current - 1)

1.4 無常損失的數學證明

無常損失(Impermanent Loss, IL)是流動性提供者面臨的核心風險。

數學推導

初始狀態:
- 代幣 X 價格:P₀
- 代幣 Y 價格:Q₀
- 流動性提供者在池中存入:x₀ 個 X 和 y₀ 個 Y
- 總價值:V₀ = x₀ × P₀ + y₀ × Q₀

假設:
- x₀ × y₀ = k(恆定乘積)
- y₀ = k / x₀

LP 初始份額:
x₀ = √(k)
y₀ = √(k)

價格變化後(P₀ → P₁):
- X 價格上漲
- Y 價格下跌(假設 Q₀ 不變)

最終池子狀態(根據恆定乘積):
x₁ = √(k × P₀ / P₁)
y₁ = √(k × P₁ / P₀)

LP 的持倉價值:
V_LP = x₁ × P₁ + y₁ × Q₀
     = √k × √P₀ × √P₁ + √k × √P₁ × Q₀ / √P₀
     = √k × √P₁ × (√P₀ + Q₀ / √P₀)

HODL(不做 LP)的價值:
V_HODL = x₀ × P₁ + y₀ × Q₀
       = √k × P₁ + √k × Q₀
       = √k × (P₁ + Q₀)

無常損失:
IL = V_LP / V_HODL - 1
    = (P₁ × (√P₀ + Q₀/√P₀)) / (P₁ + Q₀) - 1

簡化(假設初始 1:1 價值,P₁ = P₀):
IL = (P₀ × 2√P₀) / (2P₀) - 1 = √P₀/P₀ - 1 = 1/√P₀ - 1

無常損失數值表

不同價格變化下的無常損失:

| 價格變化  | 無常損失  |
|---------|----------|
| -50%    | -2.93%   |
| -25%    | -1.25%   |
| 0%      | 0%       |
| +25%    | -1.25%   |
| +50%    | -2.93%   |
| +100%   | -5.72%   |
| +200%   | -13.40%  |
| +400%   | -25.47%  |
| +900%   | -42.45%  |

注意:無常損失總是負的(除非價格不變)

第二章:借貸協議利率模型

2.1 線性利率模型

Compound 採用最簡單的線性利率模型。

數學公式

def compound_interest_model(
    cash,           # 池中可用現金
    borrow,         # 已借出金額
    utilization,     # 利用率 = borrow / (cash + borrow)
    kink,            # 轉折點利用率
    rate_at_kink,    # 轉折點利率
    rate_multiplier, # 利率乘數
    base_rate_per_block,  # 基礎年利率
):
    """
    Compound 的線性利率模型
    
    借款利率 = min(
        rate_multiplier × 利用率 + base_rate,
        max_rate
    )
    
    當利用率 < kink:
        借款利率 = rate_multiplier × 利用率 + base_rate
    當利用率 >= kink:
        借款利率 = kink × rate_multiplier + base_rate + 
                  (利用率 - kink) × jump_multiplier
    """
    
    if utilization <= kink:
        borrow_rate = rate_multiplier * utilization + base_rate_per_block
    else:
        borrow_rate = (
            rate_multiplier * kink + 
            base_rate_per_block + 
            (utilization - kink) * jump_multiplier
        )
    
    return borrow_rate

# Compound 典型參數(ETH):
# baseRatePerYear = 0
# multiplierPerYear = 0.04 (4%)
# kink = 0.8 (80%)
# jumpMultiplierPerYear = 2.5 (250%)

利率曲線圖示

借款利率 (%/年)
    │
250%│                                           ●
    │                                      ●
    │                                 ●
    │
 80%│_______________●________________
    │              kink (80%)
    │         ●
    │
  4%│____●
    │
    └────┬────┬────┬────┬────┬────→ 利用率
       0%   20%  40%  60%  80%  100%

2.2 Aave V3 的利率模型

Aave V3 採用更複雜的利率模型,包含多個參數:

class AaveInterestModel:
    def __init__(
        self,
        optimal_utilization=0.8,      # 80% 最佳利用率
        base_variable_borrow_rate=0,  # 0% 基礎利率
        variable_rate_slope1=0.04,    # 4% 第一斜率
        variable_rate_slope2=0.60,    # 60% 第二斜率
        stable_rate_slope1=0.025,     # 2.5% 穩定利率第一斜率
        stable_rate_slope2=0.75,      # 75% 穩定利率第二斜率
    ):
        self.optimal = optimal_utilization
        self.base_rate = base_variable_borrow_rate
        self.slope1 = variable_rate_slope1
        self.slope2 = variable_rate_slope2
        self.stable_slope1 = stable_rate_slope1
        self.stable_slope2 = stable_rate_slope2
    
    def calculate_borrow_rate(self, utilization, is_stable=False):
        """
        計算借款利率
        
        參數:
        - utilization: 利用率 (0-1)
        - is_stable: 是否為穩定利率借款
        """
        if is_stable:
            slope1 = self.stable_slope1
            slope2 = self.stable_slope2
        else:
            slope1 = self.slope1
            slope2 = self.slope2
        
        if utilization <= self.optimal:
            # 在最佳利用率以下
            rate = self.base_rate + utilization * slope1 / self.optimal
        else:
            # 超過最佳利用率
            rate = (
                self.base_rate + 
                slope1 + 
                (utilization - self.optimal) * slope2 / (1 - self.optimal)
            )
        
        return rate
    
    def calculate_supply_rate(self, utilization, borrow_rate, reserve_factor=0.15):
        """
        計算存款利率
        
        APR = utilization × borrow_rate × (1 - reserve_factor)
        """
        return utilization * borrow_rate * (1 - reserve_factor)

Aave V3 利率參數示例(2024年數據)

主要資產的 Aave V3 利率參數:

USDC:
- Optimal U: 80%
- Base Rate: 0%
- Slope1: 4%
- Slope2: 60%
- Reserve Factor: 15%

WBTC:
- Optimal U: 65%
- Base Rate: 0%
- Slope1: 3.5%
- Slope2: 50%
- Reserve Factor: 20%

ETH:
- Optimal U: 80%
- Base Rate: 1%
- Slope1: 3%
- Slope2: 50%
- Reserve Factor: 15%

| 利用率  | USDC 借款利率 | ETH 借款利率 |
|--------|-------------|-------------|
| 20%    | 1.0%        | 2.0%        |
| 50%    | 2.5%        | 3.0%        |
| 80%    | 4.0%        | 4.0%        |
| 90%    | 9.0%        | 8.5%        |
| 100%   | 16.0%       | 15.5%       |

2.3 連續複利利率模型

DeFi 協議通常使用連續複利作為內部利率表示:

import math

def continuous_to_apr(rate_continuous):
    """連續複利轉年化百分比率"""
    return math.exp(rate_continuous) - 1

def apr_to_continuous(rate_apr):
    """年化百分比率轉連續複利"""
    return math.log(1 + rate_apr)

def calculate_accrued_interest(
    principal,      # 本金
    rate_apr,        # 年化利率
    time_years       # 時間(年)
):
    """
    計算複利利息
    """
    # 離散複利(年)
    future_value = principal * (1 + rate_apr) ** time_years
    
    # 連續複利
    rate_cont = apr_to_continuous(rate_apr)
    future_value_cont = principal * math.exp(rate_cont * time_years)
    
    return future_value_cont

# 示例
principal = 10_000  # 10,000 USDC
rate_apr = 0.05     # 5% 年化
time_years = 2      # 2 年

interest = calculate_accrued_interest(principal, rate_apr, time_years)
print(f"2年後總額: {interest:.2f} USDC")
# 輸出: 2年後總額: 11051.27 USDC

第三章:清算機制量化分析

3.1 健康因子與清算閾值

健康因子(Health Factor, HF)是借貸協議風險管理的核心指標:

class LiquidationCalculator:
    def __init__(
        self,
        collateral_factor,    # 抵押率
        liquidation_threshold, # 清算閾值
        liquidation_penalty,   # 清算罰款
    ):
        self.collateral_factor = collateral_factor
        self.liquidation_threshold = liquidation_threshold
        self.liquidation_penalty = liquidation_penalty
    
    def calculate_health_factor(
        self,
        collateral_value,     # 抵押品價值
        borrow_value,         # 借款價值
    ):
        """
        健康因子 = (抵押品價值 × 清算閾值) / 借款價值
        
        HF > 1.0: 健康狀態
        HF <= 1.0: 可被清算
        """
        if borrow_value == 0:
            return float('inf')
        
        return (collateral_value * self.liquidation_threshold) / borrow_value
    
    def calculate_liquidation_threshold(
        self,
        collateral_value,
        liquidation_threshold,
    ):
        """
        計算可清算的借款價值上限
        """
        return (collateral_value * liquidation_threshold)
    
    def calculate_liquidation_price(
        self,
        collateral_amount,    # 抵押品數量
        collateral_price,     # 抵押品初始價格
        collateral_factor,
        borrow_value,         # 借款金額
    ):
        """
        計算觸發清算的抵押品價格
        """
        # HF = 1 時觸發清算
        # collateral_value × liquidation_threshold = borrow_value
        # collateral_amount × price × liquidation_threshold = borrow_value
        # price = borrow_value / (collateral_amount × liquidation_threshold)
        
        price_liquidation = borrow_value / (
            collateral_amount * self.collateral_factor
        )
        
        # 計算從初始價格到清算價格的跌幅
        drop_percentage = (collateral_price - price_liquidation) / collateral_price
        
        return price_liquidation, drop_percentage

健康因子數值示例

Aave V3 USDC 清算參數:
- 清算閾值 (LT): 80%
- 清算罰款 (LP): 10%

借款人情境:
- 存入 10 ETH(假設 ETH = $3,500)
- 抵押品價值 = $35,000
- 最大可借款 = $35,000 × 0.80 = $28,000

假設借款 $20,000 DAI:
健康因子 = ($35,000 × 0.80) / $20,000 = 1.4

清算觸發點:
當健康因子 = 1.0
$35,000 × 0.80 / (借款額) = 1.0
借款額 = $28,000

當 ETH 跌破 $28,000 / (10 × 0.80) = $3,500 × 0.8 = $2,800 時
健康因子 = 1.0,觸發清算

3.2 清算收益計算

清算人能夠獲得清算罰款作為收益:

def calculate_liquidation_profit(
    collateral_amount,
    collateral_price,
    debt_to_cover,           # 需償還的債務
    liquidation_bonus,       # 清算獎勵(>1)
    liquidator_fee=0,         # 清算人額外費用
):
    """
    計算清算人的理論收益
    """
    # 清算人需償還的債務
    debt_repaid = debt_to_cover
    
    # 清算人收到的抵押品
    collateral_received = debt_to_cover * liquidation_bonus
    
    # 抵押品市值
    collateral_value = collateral_received * collateral_price
    
    # 清算人成本
    cost = debt_repaid + liquidator_fee
    
    # 利潤
    profit = collateral_value - cost
    
    # 利潤率
    profit_rate = profit / cost if cost > 0 else 0
    
    return collateral_received, profit, profit_rate

# 示例
collateral_amount = 10      # 10 ETH
collateral_price = 3000     # $3000
debt_to_cover = 25000       # 需償還 $25,000 DAI
liquidation_bonus = 1.1     # 10% 獎勵

collateral_received, profit, rate = calculate_liquidation_profit(
    collateral_amount,
    collateral_price,
    debt_to_cover,
    liquidation_bonus
)

print(f"清算人收到的 ETH: {collateral_received:.4f}")
print(f"清算人利潤: ${profit:.2f}")
print(f"利潤率: {rate*100:.2f}%")
# 輸出:
# 清算人收到的 ETH: 9.1667
# 清算人利潤: $2500.00
# 利潤率: 10.00%

3.3 級聯清算模型

在市場急劇下跌時,可能發生級聯清算:

class CascadingLiquidation:
    def simulate_cascade(
        initial_price,
        price_drop_rate,      # 每步驟價格下跌率
        liquidation_threshold,
        market_liquidity,     # 市場流動性
        total_collateral,
        total_debt,
        max_steps=100,
    ):
        """
        模擬級聯清算過程
        
        當抵押品價格下跌觸發清算時:
        1. 清算人拋售抵押品
        2. 供應增加導致價格進一步下跌
        3. 更多頭寸觸發清算
        """
        results = []
        current_price = initial_price
        remaining_collateral = total_collateral
        remaining_debt = total_debt
        
        for step in range(max_steps):
            # 計算有多少頭寸處於危險邊緣
            dangerous_positions = (
                remaining_collateral * price_drop_rate * 
                (1 - liquidation_threshold)
            )
            
            # 計算拋售壓力
            selling_pressure = dangerous_positions * market_liquidity
            
            # 更新價格
            price_change = selling_pressure * price_drop_rate
            current_price = current_price * (1 - price_change)
            
            # 計算清算量
            liquidation_amount = min(
                dangerous_positions,
                remaining_debt
            )
            
            results.append({
                'step': step,
                'price': current_price,
                'price_drop': (initial_price - current_price) / initial_price,
                'liquidated': liquidation_amount,
                'remaining_debt': remaining_debt - liquidation_amount,
            })
            
            remaining_debt -= liquidation_amount
            
            if remaining_debt <= 0:
                break
        
        return results

# 級聯清算示例
results = simulate_cascade(
    initial_price=3000,
    price_drop_rate=0.05,
    liquidation_threshold=0.8,
    market_liquidity=0.1,
    total_collateral=1_000_000,  # 假設 100 萬 ETH
    total_debt=2_500_000_000,    # 假設 25 億美元
)

# 結果分析
for r in results[:10]:
    print(f"步驟 {r['step']}: 價格 ${r['price']:.2f}, "
          f"下跌 {r['price_drop']*100:.2f}%, "
          f"清算 ${r['liquidated']/1e6:.2f}M")

第四章:收益率數學模型

4.1 收益率來源分解

DeFi 收益率可分解為多個來源:

class YieldDecomposition:
    @staticmethod
    def decompose_yield(
        trading_fees_apr,      # 交易費用收益
        lending_borrow_apr,     # 借貸利差收益
        staking_rewards_apr,    # 質押獎勵
        token_incentives_apr,   # 代幣激勵
        mev_revenue_apr,       # MEV 收益
        rebasing_rewards_apr=0,# 再質押獎勵(Rebasing)
    ):
        """
        總收益率 = 所有來源之和
        """
        total = (
            trading_fees_apr +
            lending_borrow_apr +
            staking_rewards_apr +
            token_incentives_apr +
            mev_revenue_apr +
            rebasing_rewards_apr
        )
        
        return {
            'total_apr': total,
            'components': {
                'trading_fees': trading_fees_apr,
                'lending_borrow': lending_borrow_apr,
                'staking': staking_rewards_apr,
                'token_incentives': token_incentives_apr,
                'mev': mev_revenue_apr,
                'rebasing': rebasing_rewards_apr,
            },
            'weights': {
                'trading_fees': trading_fees_apr / total if total > 0 else 0,
                'lending_borrow': lending_borrow_apr / total if total > 0 else 0,
                # ...
            }
        }

# 示例:Uniswap V3 ETH/USDC 集中流動性頭寸
decomposition = YieldDecomposition.decompose_yield(
    trading_fees_apr=0.15,      # 15% 來自交易費用
    lending_borrow_apr=0,       # 無借貸利差
    staking_rewards_apr=0.05,   # 5% 來自質押獎勵(如有)
    token_incentives_apr=0.02,  # 2% 來自代幣激勵
    mev_revenue_apr=0.01,       # 1% 來自 MEV
)

print(f"總APR: {decomposition['total_apr']*100:.2f}%")

4.2 年化收益率計算

import math

def calculate_apr_from_apy(apy, compounding_frequency=365):
    """APY 轉 APR"""
    return ((1 + apy) ** (1 / compounding_frequency) - 1) * compounding_frequency

def calculate_apy_from_apr(apr, compounding_frequency=365):
    """APR 轉 APY"""
    return (1 + apr / compounding_frequency) ** compounding_frequency - 1

def calculate_effective_apy(
    principal,
    daily_rate,       # 日收益率
    days,
    reinvest=True,
):
    """
    計算有效收益
    
    參數:
    - principal: 初始本金
    - daily_rate: 日收益率
    - days: 天數
    - reinvest: 是否複投
    """
    if reinvest:
        # 每日複投
        final_value = principal * (1 + daily_rate) ** days
    else:
        # 簡單利息
        final_value = principal * (1 + daily_rate * days)
    
    total_return = (final_value - principal) / principal
    apy = (1 + daily_rate) ** 365 - 1
    
    return final_value, total_return, apy

# 示例
principal = 10_000
daily_rate = 0.001  # 0.1% 日收益
days = 30

final, total_return, apy = calculate_effective_apy(
    principal, daily_rate, days, reinvest=True
)

print(f"30天後本金+收益: ${final:.2f}")
print(f"30天總收益率: {total_return*100:.2f}%")
print(f"年化收益率 (APY): {apy*100:.2f}%")
# 輸出:
# 30天後本金+收益: $13,048.13
# 30天總收益率: 30.48%
# 年化收益率 (APY): 2878.51%

4.3 超額收益與資金效率

class CapitalEfficiency:
    @staticmethod
    def calculate_leverage_multiplier(
        collateral,
        borrowed,
    ):
        """
        槓桿倍數 = 總敞口 / 自有資金
        """
        total_exposure = collateral + borrowed
        equity = collateral
        
        return total_exposure / equity
    
    @staticmethod
    def calculate_liquidation_margin(
        entry_price,
        liquidation_price,
        collateral,
    ):
        """
        清算邊際 = (進場價 - 清算價) / 進場價
        """
        if entry_price == 0:
            return 0
        return (entry_price - liquidation_price) / entry_price
    
    @staticmethod
    def calculate_max_leverage(
        liquidation_threshold,
        maintenance_margin,
    ):
        """
        最大槓桿倍數計算
        
        清算邊際 = 1 - 清算閾值
        最大槓桿 = 1 / 清算邊際
        """
        safety_margin = 1 - liquidation_threshold
        return 1 / safety_margin

# 最大槓桿示例(Aave USDC)
max_leverage = CapitalEfficiency.calculate_max_leverage(
    liquidation_threshold=0.80,
    maintenance_margin=0.05,
)
print(f"最大槓桿: {max_leverage:.1f}x")
# 輸出: 最大槓桿: 5.0x

第五章:風險量化模型

5.1 VaR(風險值)計算

import numpy as np
from scipy import stats

class ValueAtRisk:
    def __init__(self, returns):
        self.returns = np.array(returns)
        self.mean = np.mean(self.returns)
        self.std = np.std(self.returns)
    
    def parametric_var(self, confidence=0.95, horizon=1):
        """
        參數法 VaR(基於常態分佈)
        
        VaR = μ - z_α × σ × √t
        """
        z = stats.norm.ppf(1 - confidence)
        var = self.mean * horizon - z * self.std * np.sqrt(horizon)
        return -var  # 轉為正值表示潛在損失
    
    def historical_var(self, confidence=0.95, horizon=1):
        """
        歷史模擬法 VaR
        """
        sorted_returns = np.sort(self.returns * horizon)
        index = int((1 - confidence) * len(sorted_returns))
        return -sorted_returns[index]
    
    def monte_carlo_var(self, confidence=0.95, simulations=10000):
        """
        蒙特卡羅模擬 VaR
        """
        simulated_returns = np.random.normal(
            self.mean, self.std, simulations
        )
        return -np.percentile(simulated_returns, (1 - confidence) * 100)
    
    def expected_shortfall(self, confidence=0.95):
        """
        Expected Shortfall (CVaR) - 平均超額損失
        
        ES = E[Loss | Loss > VaR]
        """
        var = self.parametric_var(confidence)
        z = stats.norm.ppf(1 - confidence)
        
        # CVaR = -μ + σ × (φ(z) / (1-α))
        # 其中 φ(z) 是標準常態分佈的 PDF
        phi_z = stats.norm.pdf(z)
        es = -self.mean + self.std * phi_z / (1 - confidence)
        
        return es

# 示例:計算 ETH 質押收益的 VaR
eth_returns = [
    0.003, 0.002, 0.004, -0.001, 0.002,
    0.003, 0.001, 0.002, 0.003, 0.002,
    # ... 更多歷史數據
] * 36  # 一年數據

var_calc = ValueAtRisk(eth_returns)

print(f"95% VaR (日): {var_calc.parametric_var(0.95)*100:.4f}%")
print(f"99% VaR (日): {var_calc.parametric_var(0.99)*100:.4f}%")
print(f"95% CVaR (日): {var_calc.expected_shortfall(0.95)*100:.4f}%")

5.2 流動性風險量化

class LiquidityRisk:
    @staticmethod
    def calculate_slippage_cost(
        pool_size,             # 池子規模
        trade_size,            # 交易規模
        fee_rate=0.003,        # 費用率
    ):
        """
        計算滑點成本
        """
        # 恆定乘積模型
        dx_fee = trade_size * fee_rate
        dx_net = trade_size - dx_fee
        
        # 輸出計算
        dy = pool_size * dx_net / (pool_size + dx_net)
        spot_price = 1
        execution_price = dy / trade_size
        
        slippage = (spot_price - execution_price) / spot_price
        
        return slippage, slippage * trade_size
    
    @staticmethod
    def calculate_market_impact(
        daily_volume,
        trade_size,
        volatility,
        illiquidity_coef=0.1,
    ):
        """
        計算市場衝擊
        
        市場衝擊 ∝ σ × √(Q/V) × ILLIQ
        其中:
        - σ: 波動率
        - Q: 交易量
        - V: 日成交量
        - ILLIQ: 非流動性係數
        """
        ratio = trade_size / daily_volume
        market_impact = volatility * np.sqrt(ratio) * illiquidity_coef
        
        return market_impact
    
    @staticmethod
    def estimate_liquidation_cost(
        position_size,
        market_depth,           # 市場深度 ($/price_unit)
        liquidation_time,       # 預計清算時間
        volatility=0.02,        # 波動率
    ):
        """
        估計清算的流動性成本
        
        清算成本 = Price × (1 - e^(-depth × time))
        """
        base_cost = position_size * (
            1 - np.exp(-market_depth * liquidation_time / position_size)
        )
        
        # 加入波動性風險溢價
        volatility_cost = position_size * volatility * np.sqrt(liquidation_time)
        
        return base_cost + volatility_cost

# 示例
cost, cost_amount = LiquidityRisk.calculate_slippage_cost(
    pool_size=10_000_000,   # 1000萬美元
    trade_size=1_000_000,   # 100萬美元交易
    fee_rate=0.003,
)

print(f"滑點: {cost*100:.4f}%")
print(f"滑點成本: ${cost_amount:.2f}")
# 輸出:
# 滑點: 0.2932%
# 滑點成本: $2,932.03

5.3 跨協議風險傳染模型

class RiskContagion:
    @staticmethod
    def simulate_contagion(
        protocols,            # 協議列表
        exposures,             # 相互敞口矩陣
        initial_shock,         # 初始衝擊
        contagion_probability=0.5,
        rounds=10,
    ):
        """
        模擬風險在 DeFi 協議間的傳染
        
        使用網路傳染模型:
        S(t+1) = β × M × S(t) × (1 - S(t))
        其中:
        - β: 傳染率
        - M: 敞口矩陣
        - S: 已受影響協議比例
        """
        n = len(protocols)
        affected = [False] * n
        affected[initial_shock] = True
        history = [affected.copy()]
        
        for r in range(rounds):
            new_affected = affected.copy()
            
            for i in range(n):
                if not affected[i]:
                    # 檢查是否有敞口感染
                    exposure_risk = sum(
                        exposures[i][j] * affected[j]
                        for j in range(n)
                    ) / sum(exposures[i])
                    
                    if exposure_risk > 0 and np.random.random() < contagion_probability:
                        new_affected[i] = True
            
            affected = new_affected
            history.append(affected.copy())
        
        return history

# 敞口矩陣示例(3個協議)
# 協議 A、B、C 相互之間的敞口
exposures = [
    [0, 0.3, 0.2],   # A對A、B、C的敞口
    [0.4, 0, 0.1],   # B對A、B、C的敞口
    [0.2, 0.3, 0],   # C對A、B、C的敞口
]

protocols = ['Aave', 'Compound', 'MakerDAO']
history = RiskContagion.simulate_contagion(
    protocols, exposures,
    initial_shock=0,  # A受到初始衝擊
    contagion_probability=0.3,
    rounds=5,
)

for i, h in enumerate(history):
    affected_names = [protocols[j] for j in range(len(protocols)) if h[j]]
    print(f"輪次 {i}: {affected_names}")

第六章:實際應用案例

6.1 Uniswap V3 頭寸分析工具

class UniswapV3PositionAnalyzer:
    def __init__(self, position_data, price_data):
        self.position = position_data
        self.prices = price_data
    
    def calculate_fees_earned(self):
        """計算已累積費用"""
        token0_fees = self.position.get('unclaimedFees_token0', 0)
        token1_fees = self.position.get('unclaimedFees_token1', 0)
        
        return {
            'token0': token0_fees,
            'token1': token1_fees,
            'total_usd': (
                token0_fees * self.prices['token0'] +
                token1_fees * self.prices['token1']
            )
        }
    
    def calculate_impermanent_loss(self):
        """計算無常損失"""
        amount0 = self.position['amount0']
        amount1 = self.position['amount1']
        price_ratio = self.prices['current'] / self.prices['initial']
        
        # 當前 LP 持倉價值
        lp_value = (
            amount0 * self.prices['current'] +
            amount1
        )
        
        # HODL 持倉價值
        hodl_value = (
            amount0 * self.prices['current'] +
            amount1 * self.prices['current'] / price_ratio
        )
        
        il = (lp_value - hodl_value) / hodl_value
        
        return {
            'il_percentage': il * 100,
            'il_amount': lp_value - hodl_value,
        }
    
    def calculate_net_value(self):
        """計算頭寸淨值(扣除無常損失+費用)"""
        fees = self.calculate_fees_earned()
        il = self.calculate_impermanent_loss()
        
        hodl_value = (
            self.position['amount0'] * self.prices['current'] +
            self.position['amount1']
        )
        
        net_value = hodl_value + fees['total_usd'] + il['il_amount']
        
        return net_value, il, fees

6.2 Aave 借款優化策略

class AaveBorrowOptimizer:
    def find_optimal_allocation(
        collateral_amount,
        available_assets,
        target_leverage,
        risk_tolerance,
    ):
        """
        找到最優的抵押借款配置
        
        目標:最大化收益同時控制風險
        """
        results = []
        
        for asset in available_assets:
            # 計算該資產的借款利率
            borrow_rate = asset['borrow_rate']
            
            # 計算收益資產的供應利率
            supply_rate = asset['supply_rate']
            
            # 計算利差收益
            spread = supply_rate - borrow_rate
            
            # 考慮波動性調整
            volatility = asset['volatility']
            risk_adjusted_spread = spread / (volatility ** risk_tolerance)
            
            results.append({
                'asset': asset['symbol'],
                'borrow_rate': borrow_rate,
                'supply_rate': supply_rate,
                'spread': spread,
                'risk_adjusted_spread': risk_adjusted_spread,
            })
        
        # 按風險調整利差排序
        results.sort(key=lambda x: x['risk_adjusted_spread'], reverse=True)
        
        return results
    
    def calculate_health_factor_safe_borrow(
        collateral_amount,
        collateral_value,
        collateral_factor,
        borrow_amount,
        borrow_price,
    ):
        """
        計算安全的借款額度以維持目標健康因子
        """
        # HF = (collateral × price × factor) / borrow
        # 目標 HF = 2.0
        
        target_hf = 2.0
        max_borrow = (collateral_value * collateral_factor) / target_hf
        
        return max_borrow

結論

DeFi 協議的數學模型是這個生態系統運作的核心。從 AMM 的定價公式到借貸協議的利率模型,從清算機制的量化分析到風險管理框架,這些數學工具使去中心化金融服務成為可能。

理解這些模型不僅對於開發者和研究者重要,對於普通用戶同樣關鍵。只有深入了解無常損失的由來、利率如何計算、以及清算機制如何運作,才能在 DeFi 空間做出明智的決策。

隨著 DeFi 領域的不斷創新,新的數學模型和金融工具將持續湧現。但無論形式如何演變,量化分析的基礎——機率論、隨機微積分、最優化理論——將永遠是 DeFi 風險管理的基石。

參考文獻

  1. Uniswap V3 Core Technical Documentation
  2. Curve Finance Whitepaper - StableSwap
  3. Compound Finance Whitepaper v2
  4. Aave V3 Technical Paper
  5. "AMM數學推導" - 學術論文
  6. "清算機制的量化風險分析" - 金融工程研究
  7. Ethereum Yellow Paper
  8. DeFi Llama Protocol Data
  9. Dune Analytics Dashboard
  10. Flashbots MEV Research

延伸閱讀與來源

這篇文章對您有幫助嗎?

評論

發表評論

注意:由於這是靜態網站,您的評論將儲存在本地瀏覽器中,不會公開顯示。

目前尚無評論,成為第一個發表評論的人吧!