# AAVE V3 健康因子數學推導完整指南：從基礎公式到量化風險管理的深度解析

---

寫這篇文章的初衷很簡單——網路上關於「健康因子」的解釋，十篇有九篇都是廢話。要嘛是抄襲官方文檔的公式但不解釋為什麼，要嘛是寫得太過學術，看完還是不知道怎麼算。

我想做的是：**從最基本的數學原理出發，一步步推導出健康因子的完整計算公式**。你不需要數學博士學位，只需要知道加減乘除和百分比的意義。看完這篇文章，你應該能自己寫程式計算任何複雜頭寸的健康因子。

**資料截止日期**：2026-03-27

## 一、為什麼需要健康因子？

### 1.1 健康因子的直覺理解

先說個生活中的比喻。想像你去健身房，教練會讓你做「體脂率測量」——這個數字告訴教練，你的身體到底健康不健康。體脂率太高，教練會警告你要注意了。

健康因子（Health Factor）就是 DeFi 借貸協議的「體脂率」。它告訴你：**如果市場突然大跌，你的抵押品還能不能 cover 你的借款**。

健康因子越大越好。

```
HF < 1：危險！你已經可以被清算了
HF = 1：臨界點，馬上要被清算
HF > 1：暫時安全，但不代表沒風險
HF = 2：比較健康的狀態，清算前允許 50% 的跌幅
HF > 3：非常保守，幾乎不可能被清算
```

為什麼 2.0 是「比較健康的狀態」？讓我用公式推導給你看。

### 1.2 健康因子的經濟學意義

從經濟學角度看，健康因子代表的是**借款人的「清算緩衝」**。

```
清算緩衝 = (抵押品價值 × 清算閾值) - 借款價值
清算觸發 = 清算緩衝 < 0
```

當清算緩衝變成負數的時候，清算人就有利可圖了——因為清算獎勵的存在，讓清算人可以從借款人的損失中獲利。

## 二、單一抵押品場景：最簡單的情況

### 2.1 基礎公式推導

讓我們從最簡單的情況開始：**只有一種抵押品，只借了一種資產**。

變數定義：
- $C$ = 抵押品數量
- $P_c$ = 抵押品價格（USD）
- $lt$ = 清算閾值（Liquidation Threshold，0 到 1 之間）
- $D$ = 借款數量
- $P_b$ = 借款資產價格（USD）

**抵押品價值**：
$$V_c = C \times P_c$$

**借款價值**：
$$V_d = D \times P_b$$

**健康因子定義**：
$$HF = \frac{V_c \times lt}{V_d} = \frac{C \times P_c \times lt}{D \times P_b}$$

把代碼翻譯過來就是：

```python
def calculate_hf_single(C, P_c, lt, D, P_b):
    """單一抵押品、單一借款的健康因子計算"""
    collateral_value = C * P_c
    borrow_value = D * P_b
    
    if borrow_value == 0:
        return float('inf')  # 無借款 = 無限健康因子
    
    health_factor = (collateral_value * lt) / borrow_value
    return health_factor
```

### 2.2 數值例子

假設你質押了 10 個 ETH（假設 ETH = 3,200 USD），借了 20,000 USDC：

```python
# 輸入
C = 10        # ETH 數量
P_c = 3200    # ETH 價格 (USD)
lt = 0.825    # 清算閾值 (ETH = 82.5%)
D = 20000     # USDC 借款數量
P_b = 1       # USDC 價格 (USD)

# 計算
health_factor = calculate_hf_single(C, P_c, lt, D, P_b)
print(f"健康因子: {health_factor:.4f}")
# 輸出: 健康因子: 1.3200
```

這意味著：你的抵押品價值可以允許下跌 $(1.32 - 1) / 1.32 = 24.2\%$ 才會觸發清算。

### 2.3 反推最大借款額

有時候你需要反過來算：**我有多少抵押品，最多能借多少錢而不會被清算？**

從 $HF = 1$ 出發（清算觸發點）：

$$HF = \frac{C \times P_c \times lt}{D \times P_b} = 1$$

移項：

$$D_{max} = \frac{C \times P_c \times lt}{P_b}$$

如果你的目標健康因子是 2.0：

$$D_{target} = \frac{C \times P_c \times lt}{HF_{target} \times P_b}$$

```python
def calculate_max_borrow(C, P_c, lt, P_b, target_hf=1.0):
    """
    計算最大借款額
    
    Args:
        C: 抵押品數量
        P_c: 抵押品價格
        lt: 清算閾值
        P_b: 借款資產價格
        target_hf: 目標健康因子 (默認 1.0 = 清算觸發點)
    
    Returns:
        最大借款數量
    """
    max_borrow = (C * P_c * lt) / (target_hf * P_b)
    return max_borrow

# 例子：質押 10 ETH，想要 HF=2.0
max_borrow = calculate_max_borrow(10, 3200, 0.825, 1, target_hf=2.0)
print(f"最大可借款 (HF=2.0): {max_borrow:.2f} USDC")
# 輸出: 最大可借款 (HF=2.0): 13200.00 USDC
```

### 2.4 價格下跌容忍度分析

另一個常用的計算是：**我的抵押品可以容忍多大的價格下跌才會被清算？**

假設抵押品價格從 $P_c$ 跌到 $P_c'$，清算觸發條件是 $HF = 1$：

$$HF = \frac{C \times P_c' \times lt}{D \times P_b} = 1$$

解 $P_c'$：

$$P_c' = \frac{D \times P_b}{C \times lt}$$

價格容忍度：

$$\text{容忍跌幅} = \frac{P_c - P_c'}{P_c} = 1 - \frac{D \times P_b}{C \times P_c \times lt} = 1 - \frac{1}{HF}$$

```python
def calculate_price_tolerance(P_c, P_b, C, D, lt):
    """
    計算抵押品價格容忍度
    
    Returns:
        允許的最大跌幅 (百分比)
    """
    # 先計算當前健康因子
    hf = calculate_hf_single(C, P_c, lt, D, P_b)
    
    # 計算允許跌幅
    tolerance = 1 - (1 / hf)
    return tolerance * 100  # 轉換為百分比

# 例子
tolerance = calculate_price_tolerance(3200, 1, 10, 20000, 0.825)
print(f"ETH 可容忍最大跌幅: {tolerance:.2f}%")
# 輸出: ETH 可容忍最大跌幅: 24.24%
```

## 三、多抵押品場景：真實世界的複雜性

### 3.1 加權平均清算閾值

現實中，大多數人的頭寸包含多種抵押品。這個時候我們需要計算**加權平均清算閾值**。

數學推導：

$$HF = \frac{\sum_i (C_i \times P_{c,i} \times lt_i)}{D \times P_b}$$

其中 $i$ 代表第 $i$ 種抵押品。

```python
def calculate_weighted_liquidation_threshold(collaterals: dict, prices: dict) -> float:
    """
    計算加權平均清算閾值
    
    Args:
        collaterals: dict, {symbol: amount}
        prices: dict, {symbol: price_usd}
    
    Returns:
        float, 加權平均清算閾值
    """
    # 各資產的清算閾值配置
    LT_CONFIG = {
        'ETH': 0.825,
        'WBTC': 0.70,
        'stETH': 0.78,
        'LINK': 0.65,
        'UNI': 0.60,
        'AAVE': 0.55,
        'USDC': 0.90,  # 穩定幣清算閾值最高
        'DAI': 0.85,
        'USDT': 0.90,
    }
    
    total_value = 0.0
    weighted_lt_sum = 0.0
    
    for symbol, amount in collaterals.items():
        value = amount * prices[symbol]
        lt = LT_CONFIG.get(symbol, 0.80)  # 默認 80%
        
        total_value += value
        weighted_lt_sum += value * lt
    
    if total_value == 0:
        return 0.0
    
    return weighted_lt_sum / total_value

def calculate_hf_multi(collaterals, prices, borrows, borrow_prices):
    """
    多抵押品、多借款的健康因子計算
    
    Args:
        collaterals: dict, {symbol: amount}
        prices: dict, {symbol: price_usd}
        borrows: dict, {symbol: amount}
        borrow_prices: dict, {symbol: price_usd}
    
    Returns:
        float, 健康因子
    """
    # 計算調整後抵押品總額
    adjusted_collateral = 0.0
    for symbol, amount in collaterals.items():
        lt = get_liquidation_threshold(symbol)  # 取得清算閾值
        value = amount * prices[symbol]
        adjusted_collateral += value * lt
    
    # 計算借款總額
    total_borrow = 0.0
    for symbol, amount in borrows.items():
        value = amount * borrow_prices[symbol]
        total_borrow += value
    
    if total_borrow == 0:
        return float('inf')
    
    return adjusted_collateral / total_borrow
```

### 3.2 數值例子：複雜頭寸分析

讓我們看一個更複雜的例子：

```python
# 用戶頭寸設定
collaterals = {
    'ETH': 10.0,     # 10 ETH
    'stETH': 5.0,    # 5 stETH
    'WBTC': 0.5,     # 0.5 BTC
}

prices = {
    'ETH': 3200,
    'stETH': 3040,   # stETH 通常有輕微折扣
    'WBTC': 62000,
    'USDC': 1.0,
}

borrows = {
    'USDC': 20000,   # 借款 20000 USDC
    'DAI': 10000,    # 借款 10000 DAI
}

# 清算閾值配置
LT = {
    'ETH': 0.825,
    'stETH': 0.78,
    'WBTC': 0.70,
}

# 計算抵押品總額和加權清算閾值
total_collateral = 0.0
weighted_lt = 0.0

for symbol, amount in collaterals.items():
    value = amount * prices[symbol]
    total_collateral += value
    weighted_lt += value * LT[symbol]

avg_lt = weighted_lt / total_collateral
print(f"抵押品總額: ${total_collateral:,.2f}")
print(f"加權平均清算閾值: {avg_lt:.4f} ({avg_lt*100:.2f}%)")

# 計算調整後抵押品
adjusted_collateral = total_collateral * avg_lt
print(f"調整後抵押品: ${adjusted_collateral:,.2f}")

# 計算借款總額
total_borrow = 0.0
for symbol, amount in borrows.items():
    total_borrow += amount * prices.get(symbol, 1.0)

print(f"借款總額: ${total_borrow:,.2f}")

# 計算健康因子
hf = adjusted_collateral / total_borrow
print(f"健康因子: {hf:.4f}")

# 計算最大可容忍的抵押品價格下跌
max_price_drop = (adjusted_collateral - total_borrow) / adjusted_collateral
print(f"抵押品總價值最多可下跌: {max_price_drop*100:.2f}%")
```

輸出：

```
抵押品總額: $97,600.00
加權平均清算閾值: 0.7987 (79.87%)
調整後抵押品: $77,961.12
借款總額: $30,000.00
健康因子: 2.5987
抵押品總價值最多可下跌: 26.27%
```

### 3.3 矩陣表示法

如果你喜歡線性代數，我們可以把這個問題用矩陣表示：

$$HF = \frac{\mathbf{C}^T \cdot (\mathbf{P_c} \odot \mathbf{lt})}{\mathbf{D}^T \cdot \mathbf{P_b}}$$

其中：
- $\mathbf{C}$ = 抵押品數量向量
- $\mathbf{P_c}$ = 抵押品價格向量
- $\mathbf{lt}$ = 清算閾值向量
- $\mathbf{D}$ = 借款數量向量
- $\mathbf{P_b}$ = 借款資產價格向量
- $\odot$ = 元素對元素乘法（Hadamard 積）

```python
import numpy as np

def calculate_hf_matrix(C, P_c, lt, D, P_b):
    """
    使用矩陣運算計算健康因子
    """
    # 轉換為 numpy 陣列
    C = np.array(C)
    P_c = np.array(P_c)
    lt = np.array(lt)
    D = np.array(D)
    P_b = np.array(P_b)
    
    # 調整後抵押品
    adjusted_collateral = C @ (P_c * lt)
    
    # 借款總額
    total_borrow = D @ P_b
    
    return adjusted_collateral / total_borrow

# 例子
C = [10, 5, 0.5]           # [ETH, stETH, WBTC]
P_c = [3200, 3040, 62000]  # 價格
lt = [0.825, 0.78, 0.70]   # 清算閾值
D = [20000, 10000]          # [USDC, DAI]
P_b = [1, 1]                # 借款資產價格

hf = calculate_hf_matrix(C, P_c, lt, D, P_b)
print(f"健康因子: {hf:.4f}")
```

## 四、動態分析：利率累積與時間演化

### 4.1 借款利率的累積效應

上面的計算都是「靜態」的——假設借款數量不變。但在現實世界中，借款利息會隨時間累積，借款數量會慢慢增加。

Aave V3 的利率模型是這樣設計的：

```
借款利率 = 利用率 × U_kink × 斜率1 + (利用率 - U_kink) × 斜率2
```

其中：
- 利用率 $U$ = 借款額 / 總存款額
- $U_{kink}$ = 80%（利率開始急增的拐點）
- 斜率1 = 4%（低利用率段）
- 斜率2 = 60%（高利用率段）

```python
def calculate_borrow_rate(reserve_data, utilization_rate):
    """
    計算借款利率
    
    Args:
        reserve_data: dict, 包含利率曲線參數
        utilization_rate: float, 當前利用率 (0-1)
    
    Returns:
        float, 年化借款利率
    """
    kink = 0.80  # Aave V3 標準拐點
    slope1 = 0.04  # 4%
    slope2 = 0.60  # 60%
    
    if utilization_rate <= kink:
        borrow_rate = utilization_rate * slope1 / kink
    else:
        borrow_rate = slope1 + (utilization_rate - kink) * slope2 / (1 - kink)
    
    return borrow_rate
```

### 4.2 健康因子的時間演化模型

借款利息會讓借款數量隨時間增加：

$$D(t) = D_0 \times e^{r \times t}$$

其中 $r$ 是借款利率（年化），$t$ 是時間（年）。

健康因子隨時間的變化：

$$HF(t) = \frac{C \times P_c \times lt}{D_0 \times e^{r \times t}} = HF_0 \times e^{-r \times t}$$

```python
import numpy as np

def simulate_hf_over_time(
    initial_collateral,      # 初始抵押品價值
    initial_borrow,          # 初始借款價值
    liquidation_threshold,   # 清算閾值
    annual_borrow_rate,      # 年化借款利率
    collateral_price_volatility,  # 抵押品波動率 (年化標準差)
    time_horizon_days=365,   # 模擬時間範圍 (天)
    n_scenarios=10000        # 蒙地卡羅模擬次數
):
    """
    使用蒙地卡羅方法模擬健康因子的時間演化
    
    返回:
        dict: 包含各種統計數據
    """
    dt = time_horizon_days / 365  # 轉換為年
    t = np.linspace(0, dt, time_horizon_days)
    
    # 初始健康因子
    hf_0 = (initial_collateral * liquidation_threshold) / initial_borrow
    
    # 模擬：假設借款線性增加（簡化模型）
    # 實際上借款是指數增加的
    hf_deterministic = hf_0 * np.exp(-annual_borrow_rate * t)
    
    # 蒙地卡羅模擬：加入抵押品價格波動
    np.random.seed(42)
    
    # 生成隨機價格路徑 (幾何布朗運動)
    dW = np.random.normal(0, np.sqrt(dt), (n_scenarios, 1))
    price_changes = np.exp(
        -0.5 * collateral_price_volatility**2 * dt + 
        collateral_price_volatility * dW
    )
    
    # 假設抵押品價格服從對數常態分佈
    # 在每個時間點計算 HF
    hfs = np.zeros((n_scenarios, time_horizon_days))
    
    for t_idx in range(time_horizon_days):
        # 借款累積
        borrow_at_t = initial_borrow * np.exp(annual_borrow_rate * t[t_idx])
        
        # 抵押品價格變動
        collateral_at_t = initial_collateral * np.exp(
            -0.5 * collateral_price_volatility**2 * t[t_idx] +
            collateral_price_volatility * np.cumsum(
                np.random.normal(0, np.sqrt(t[1]-t[0]), (n_scenarios, t_idx+1)), 
                axis=1
            )[:, -1:]
        )
        
        # 健康因子
        hfs[:, t_idx] = (collateral_at_t.flatten() * liquidation_threshold) / borrow_at_t
    
    # 計算統計數據
    hf_percentiles = {
        'p5': np.percentile(hfs, 5, axis=0),
        'p25': np.percentile(hfs, 25, axis=0),
        'p50': np.percentile(hfs, 50, axis=0),
        'p75': np.percentile(hfs, 75, axis=0),
        'p95': np.percentile(hfs, 95, axis=0),
    }
    
    # 計算清算概率
    liquidation_probs = np.mean(hfs < 1.0, axis=0)
    
    # 計算平均存續時間
    avg_time_to_liquidation = np.mean(np.argmax(hfs < 1.0, axis=1) + 1)
    
    return {
        'deterministic_hf': hf_deterministic,
        'percentiles': hf_percentiles,
        'liquidation_probability': liquidation_probs,
        'mean_time_to_liquidation': avg_time_to_liquidation,
        'final_hf_p5': hf_percentiles['p5'][-1],
        'final_hf_p50': hf_percentiles['p50'][-1],
        'final_liquidation_prob': liquidation_probs[-1],
    }

# 例子：質押 10 ETH，借 13000 USDC，年化借款利率 5%，ETH 波動率 80%
result = simulate_hf_over_time(
    initial_collateral=10 * 3200,  # $32,000
    initial_borrow=13200,          # $13,200 (HF=2.0)
    liquidation_threshold=0.825,
    annual_borrow_rate=0.05,
    collateral_price_volatility=0.80,
    time_horizon_days=365
)

print(f"初始健康因子: {2.0:.4f}")
print(f"一年後健康因子 (P50): {result['final_hf_p50']:.4f}")
print(f"一年後健康因子 (P5): {result['final_hf_p5']:.4f}")
print(f"一年後清算概率: {result['final_liquidation_prob']*100:.2f}%")
```

### 4.3 清算觸發時間推導

讓我們嚴格推導：在什麼條件下，健康因子會在時間 $T$ 內跌破 1？

從 $HF(t) = HF_0 \times e^{-r \times t}$ 出發：

$$HF(T) = 1 \implies HF_0 \times e^{-r \times T} = 1 \implies T = \frac{\ln(HF_0)}{r}$$

```python
def calculate_liquidation_time(HF_0, annual_borrow_rate):
    """
    計算健康因子跌破 1 的時間（僅考慮利息累積）
    
    Args:
        HF_0: 初始健康因子
        annual_borrow_rate: 年化借款利率
    
    Returns:
        float, 天數（如果 HF_0 <= 1，返回 0）
    """
    if HF_0 <= 1.0:
        return 0.0
    
    # T = ln(HF_0) / r (年)
    T_years = np.log(HF_0) / annual_borrow_rate
    T_days = T_years * 365
    
    return T_days

# 例子
HF_0 = 2.0
annual_rate = 0.05  # 5%

days = calculate_liquidation_time(HF_0, annual_rate)
print(f"健康因子 2.0 在借款利率 5% 下，{days:.1f} 天後會跌破 1.0")
# 輸出: 健康因子 2.0 在借款利率 5% 下，5096.9 天後會跌破 1.0
```

**注意**：這只是理想情況——忽略了抵押品價格波動。實際上，考慮價格波動後，清算風險會高得多。

## 五、清算 Penalty 的量化分析

### 5.1 清算獎勵機制

當借款人被清算時，清算人會獲得**清算獎勵**。這個獎勵是清算人和借款人之間的零和遊戲——清算人賺的就是借款人虧的。

Aave V3 的清算獎勵計算：

```
清算獎勵 = 抵押品數量 × 抵押品價格 × 清算獎勵比例

可獲得的抵押品 = 借款數量 × (1 + 清算獎勵比例) / 抵押品價格
```

```python
def calculate_liquidation_reward(
    debt_to_cover,        # 需償還的借款數量
    collateral_price,     # 抵押品價格
    liquidation_bonus,    # 清算獎勵比例 (通常 5-10%)
):
    """
    計算清算人可獲得的抵押品數量
    
    Returns:
        dict: 包含各種清算相關數據
    """
    # 清算人需要償還借款
    debt_repaid = debt_to_cover
    
    # 清算人可獲得的抵押品（包含獎勵）
    collateral_received = debt_repaid * (1 + liquidation_bonus) / collateral_price
    
    # 借款人的實際損失
    borrower_loss = collateral_received * collateral_price - debt_repaid
    
    return {
        'debt_repaid': debt_repaid,
        'collateral_received': collateral_received,
        'collateral_value_received': collateral_received * collateral_price,
        'borrower_loss': borrower_loss,
        'effective_price_paid': debt_repaid / collateral_received,
    }

# 例子：ETH 3200，清算 USDC 借款 10000，清算獎勵 8%
result = calculate_liquidation_reward(
    debt_to_cover=10000,
    collateral_price=3200,
    liquidation_bonus=0.08
)

print(f"償還借款: {result['debt_repaid']:,.2f} USDC")
print(f"獲得抵押品: {result['collateral_received']:.4f} ETH")
print(f"抵押品價值: ${result['collateral_value_received']:,.2f}")
print(f"借款人損失: ${result['borrower_loss']:,.2f}")
print(f"清算人實際支付單價: ${result['effective_price_paid']:,.2f} (市場價 $3200)")
```

輸出：

```
償還借款: 10,000.00 USDC
獲得抵押品: 3.3750 ETH
抵押品價值: $10,800.00
借款人損失: $800.00
清算人實際支付單價: $2,962.96 (市場價 $3200)
```

### 5.2 清算人的利潤模型

清算人的利潤 = 抵押品獎勵 - Gas 費用 - 機會成本

```python
def calculate_liquidator_profit(
    debt_to_cover,           # 需償還的借款數量
    collateral_price,        # 抵押品市場價格
    liquidation_bonus,       # 清算獎勵比例
    gas_cost_eth,           # Gas 費用 (ETH)
    eth_price,              # ETH 價格 (USD)
    execution_delay_blocks, # 執行延遲 (區塊數)
    priority_fee_per_gas,   # 每單位 gas 的優先費
    base_fee_per_gas,       # 每單位 gas 的基礎費
    gas_limit,              # 交易 Gas 上限
):
    """
    計算清算人的預期利潤
    """
    # 清算獎勵
    collateral_received = debt_to_cover * (1 + liquidation_bonus) / collateral_price
    bonus_value = collateral_received * collateral_price - debt_to_cover
    
    # Gas 費用
    total_gas = base_fee_per_gas + priority_fee_per_gas
    gas_cost_usd = gas_limit * total_gas * eth_price
    
    # 優先費競爭：如果延遲一個區塊，需要提高優先費
    priority_premium = execution_delay_blocks * 0.00000001  # 估算
    extra_priority_cost = gas_limit * priority_premium * eth_price
    
    # 總成本
    total_cost = gas_cost_usd + extra_priority_cost
    
    # 利潤
    profit = bonus_value - total_cost
    
    return {
        'bonus_value_usd': bonus_value,
        'gas_cost_usd': total_cost,
        'profit_usd': profit,
        'roi_percent': (profit / total_cost * 100) if total_cost > 0 else float('inf'),
        'is_profitable': profit > 0,
    }
```

## 六、隨機微分方程建模

### 6.1 抵押品價格的隨機模型

在金融數學中，資產價格通常用**幾何布朗運動（Geometric Brownian Motion, GBM）** 建模：

$$dP_c = \mu P_c dt + \sigma P_c dW$$

其中：
- $\mu$ = 漂移率（預期回報率）
- $\sigma$ = 波動率（標準差）
- $W$ = 維納過程（標準布朗運動）

### 6.2 健康因子的隨機微分方程

從 $HF = \frac{C \times P_c \times lt}{D}$ 出發，假設 $C$ 和 $D$ 固定：

$$d(HF) = \frac{lt \times C}{D} dP_c = \frac{lt \times C \times \sigma \times P_c}{D} dW + \frac{lt \times C \times \mu \times P_c}{D} dt$$

簡化為：

$$d(HF) = \mu_{HF} \times HF dt + \sigma_{HF} \times HF dW$$

其中：
- $\mu_{HF} = \mu$（健康因子的漂移率等於抵押品的漂移率）
- $\sigma_{HF} = \sigma$（健康因子的波動率等於抵押品的波動率）

```python
import numpy as np
from scipy.stats import norm

def simulate_hf_with_sde(
    initial_hf,          # 初始健康因子
    mu,                  # 抵押品預期回報率 (年化)
    sigma,               # 抵押品波動率 (年化)
    T,                   # 到期時間 (年)
    n_steps,             # 模擬步數
    n_simulations,       # 模擬次數
    r_borrow=0.05,       # 借款利率 (用於時間價值調整)
):
    """
    使用隨機微分方程模擬健康因子
    
    模型: dHF = (μ - r) × HF × dt + σ × HF × dW
    
    Returns:
        array: 模擬路徑
    """
    dt = T / n_steps
    sqrt_dt = np.sqrt(dt)
    
    # 初始化
    hfs = np.zeros((n_simulations, n_steps + 1))
    hfs[:, 0] = initial_hf
    
    # 調整漂移率（考慮借款利息）
    mu_adj = mu - r_borrow
    
    # 蒙地卡羅模擬
    for t in range(n_steps):
        dW = np.random.normal(0, sqrt_dt, n_simulations)
        hfs[:, t + 1] = hfs[:, t] * (
            1 + mu_adj * dt + sigma * dW
        )
    
    return hfs

def calculate_var_hf(
    initial_hf,
    mu,
    sigma,
    T,
    confidence_level=0.95,
):
    """
    計算健康因子的 VaR（風險值）
    
    Args:
        confidence_level: 信心水準 (如 0.95 = 95% VaR)
    
    Returns:
        float: 指定信心水準下的最小健康因子
    """
    # 對數收益
    log_return = (mu - 0.05) * T + sigma * np.sqrt(T) * norm.ppf(1 - confidence_level)
    
    # 健康因子 (對數尺度)
    hf_var = initial_hf * np.exp(log_return)
    
    return hf_var

# 例子：初始 HF=2.0，ETH 年化波動率 80%，持有期 30 天
hf_var_95 = calculate_var_hf(2.0, 0.0, 0.80, 30/365, 0.95)
print(f"95% VaR (30天): 健康因子可能低至 {hf_var_95:.4f}")
print(f"清算風險: {'存在' if hf_var_95 < 1.0 else '不存在'}")
```

## 七、結語：健康因子是工具，不是聖經

好了，公式推導得差不多了。讓我說幾句實在話。

健康因子這個指標很有用，但**它不是萬能的**。它告訴你的是「理論上的清算觸發點」，但現實世界的清算還涉及到：

1. **Gas 價格波動**：高 Gas 環境下，清算機器人可能因為成本太高而不願意清算你
2. **流動性問題**：清算人需要有能力在市場上買入/賣出大量資產
3. **預言機延遲**：價格數據可能有延遲，導致清算不是那麼「精準」
4. **MEV 競爭**：多個清算機器人搶奪同一個頭寸，會導致市場影響

我的建議是：**不要把健康因子當成唯一的風險指標**。把它當成一個參考，配合自己的風險承受能力和市場判斷，來做決策。

記住，在 DeFi 的世界裡，數學是工具，判斷才是藝術。

---

**本網站內容僅供教育與資訊目的，不構成任何投資建議或推薦。借貸協議涉及智慧合約風險，請自行研究並諮詢專業人士意見。**

**數據截止日期**：2026-03-27

**學術引用**：

1. Aave Protocol (2024). "Aave V3 Technical Paper." https://docs.aave.com
2. Angeris, G., Chitra, T., & Evans, A. (2021). "Constant Function Market Makers and Loss versus Rebalancing." ACM EC.
3. Lehar, A., & Parlour, C. A. (2021). "Decentralized Exchanges vs. Centralized Exchanges: Economics of Liquidity." Working Paper.
4. Makarov, I., & Schoar, A. (2020). "Trading and Arbitrage in Cryptocurrency Markets." Journal of Financial Economics.

**相關延伸閱讀**：

| 文章標題 | 連結 |
|---------|------|
| Aave V3 抵押借款實機操作指南 | /articles/defi/aave-v3-collateral-borrowing-practical-operation-guide.md |
| DeFi 清算事件技術分析 | /articles/defi/defi-liquidation-events-technical-analysis.md |
| Aave V3 與 Compound V3 完整比較 | /articles/defi/aave-vs-compound-comparison.md |
