Skill 寫法圖鑑

algo-risk-var

asgard-ai-platform | 金融與投資 | 原文 | MIT

計算風險值 VaR,估計投資組合的最大損失

中文翻譯

---
name: "algo-risk-var"
description: "計算風險值(Value at Risk),估計投資組合在特定信賴水準下的最大損失。當使用者需要量化下檔風險、設定風險限額、或回報法規要求的風險指標時使用,即使他們說的是「最壞情況的損失」、「投資組合風險」或「我們最多會虧多少」也一樣。"
metadata:
  category: "WP-40 風險演算法"
  tags: ["risk", "value-at-risk", "portfolio", "risk-management"]
---

# 風險值(Value at Risk,VaR)

## 概述

VaR 估計投資組合在特定時間範圍、特定信賴水準下,可能承受的最大損失。例如:「95% 的 1 日 VaR 是 $1M」,意思是一天內虧損超過 $1M 的機率有 5%。三種方法:參數法(常態)、歷史模擬法、蒙地卡羅法。

## 何時使用

**觸發條件:**
- 為了風險管理,量化投資組合的下檔風險
- 設定交易限額和資本準備
- 法規申報(Basel III 要求以 VaR 為基礎的資本)

**何時不要用:**
- 需要知道損失在 VaR 之外「可能」有多慘時(用 CVaR/Expected Shortfall)
- 沒有價格歷史的流動性差資產(VaR 需要報酬率資料)

## 演算法

```
鐵律:VaR「不會」告訴你超過門檻之後會多慘
VaR 說的是「95% 的時間,損失不會超過 $X」。
對那最糟的 5% 情況,它「什麼都沒說」。
投資組合可能 VaR 很低,但尾端損失卻是災難性的。
一定要搭配 Expected Shortfall(CVaR)一起看,
它衡量的是尾端的平均損失。
```

### 階段 1:輸入驗證
蒐集:投資組合部位、歷史報酬率(1 年至少 250 天)、信賴水準(通常 95% 或 99%)、時間範圍(1 天或 10 天)。
**關卡:** 報酬率歷史足夠、部位以當前市價評價。

### 階段 2:核心演算法
**參數法 VaR:** VaR = -μ + zα × σ(假設報酬率服從常態)。投資組合的話:用共變異數矩陣算投資組合的 σ。

**歷史模擬法:** 1. 從歷史報酬率算出每日損益。2. 損益由小到大排序。3. VaR = 第 (1-α) 百分位的損失。

**蒙地卡羅法:** 1. 擬合報酬率分布(或直接用歷史分布)。2. 模擬 10,000 條以上的投資組合路徑。3. VaR = 模擬損失的第 (1-α) 百分位。

### 階段 3:驗證
回測:計算過去一年實際損失超過 VaR 的次數。在 95% 信賴水準下,超越率應該約 5%。使用 Kupiec 或 Christoffersen 檢定。
**關卡:** 回測的超越率在可接受範圍內。

### 階段 4:輸出
回傳 VaR 估計值,附上回測結果。

## 輸出格式

```json
{
  "var": {"amount": 1250000, "confidence": 0.95, "horizon_days": 1, "currency": "TWD"},
  "cvar": {"amount": 1800000},
  "backtest": {"exceedances": 13, "expected": 12.5, "days_tested": 250, "pass": true},
  "metadata": {"method": "historical_simulation", "portfolio_value": 50000000}
}
```

## 範例

### 輸入輸出範例
**輸入:** 投資組合價值 = $1,000,000。最近 20 筆排序過的每日報酬率(損失由大到小):
```
[-0.050, -0.040, -0.035, -0.030, -0.025, -0.020, -0.015, -0.010, -0.005, 0.000,
  0.005,  0.010,  0.015,  0.020,  0.025,  0.030,  0.035,  0.040,  0.045,  0.050]
```
信賴水準 = 95%,時間範圍 = 1 天。

**預期(歷史模擬法):**
- 第 5 百分位的索引 = floor(20 × 0.05) = 1 → return[1] = -0.040
- VaR = $1,000,000 × 0.040 = **$40,000**
- CVaR(Expected Shortfall)= 比 VaR 更糟的報酬率的平均 = (-0.050) × $1M = **$50,000**

驗證:VaR ≤ CVaR 永遠成立(尾端損失 ≥ 門檻損失)。損失大於 VaR 的筆數,應該 ≤ 觀測值的 5%(20 筆中的 1 筆)。

### 邊界情況
| 輸入 | 預期 | 原因 |
|-------|----------|-----|
| 正常的市場狀況 | VaR 看起來夠用 | 但會漏掉尾端事件 |
| 歷史中有類似 2008 的危機 | 歷史法算出較高的 VaR | 如果危機在觀測窗口內,就能捕捉到肥尾 |
| 歷史非常短(30 天) | VaR 不可靠 | 尾端估計的資料不足 |

## 常見陷阱

- **常態假設**:參數法 VaR 假設報酬率服從常態。金融報酬率有肥尾,參數法 VaR 會「低估」尾端風險。
- **歷史窗口**:歷史模擬法的好壞取決於歷史。如果過去 250 天很平靜,就算危機即將到來,VaR 還是會很低。
- **時間縮放**:只有在獨立且常態的條件下,VaR 才會以 √T 縮放。在波動大或有趨勢的市場,這個近似很差。
- **分散的假象**:用平時的相關係數算相關資產的 VaR,會低估風險。危機時相關係數會飆高(相關性崩壞)。
- **操弄 VaR**:交易員可以設計出在 VaR 下看起來安全、但尾端風險是災難性的部位。這就是為什麼監理機關還要求壓力測試。

## 參考資料

- Expected Shortfall(CVaR)的計算,見 `references/expected-shortfall.md`
- VaR 的回測方法,見 `references/backtesting.md`

英文原文

---
name: "algo-risk-var"
description: "Calculate Value at Risk to estimate maximum portfolio loss at a given confidence level. Use this skill when the user needs to quantify downside risk, set risk limits, or report regulatory risk measures — even if they say 'worst case loss', 'portfolio risk', or 'how much could we lose'."
metadata:
  category: "WP-40 風險演算法"
  tags: ["risk", "value-at-risk", "portfolio", "risk-management"]
---

# Value at Risk (VaR)

## Overview

VaR estimates the maximum loss a portfolio can suffer over a given time horizon at a specified confidence level. Example: "95% 1-day VaR of $1M" means there's a 5% chance of losing more than $1M in one day. Three methods: parametric (normal), historical simulation, Monte Carlo.

## When to Use

**Trigger conditions:**
- Quantifying portfolio downside risk for risk management
- Setting trading limits and capital reserves
- Regulatory reporting (Basel III requires VaR-based capital)

**When NOT to use:**
- When you need to know how bad losses CAN get beyond VaR (use CVaR/Expected Shortfall)
- For illiquid assets with no price history (VaR needs return data)

## Algorithm

```
IRON LAW: VaR Does NOT Tell You How Bad It Gets BEYOND the Threshold
VaR says "95% of the time, losses won't exceed $X." It says NOTHING
about the 5% worst case. A portfolio can have low VaR but catastrophic
tail losses. Always supplement with Expected Shortfall (CVaR) which
measures the average loss in the tail.
```

### Phase 1: Input Validation
Collect: portfolio positions, historical returns (min 250 days for 1Y), confidence level (typically 95% or 99%), time horizon (1 day or 10 days).
**Gate:** Sufficient return history, positions valued at current market.

### Phase 2: Core Algorithm
**Parametric VaR:** VaR = -μ + zα × σ (assumes normal returns). For portfolio: use covariance matrix for portfolio σ.

**Historical Simulation:** 1. Compute daily P&L from historical returns. 2. Sort P&L ascending. 3. VaR = the (1-α) percentile loss.

**Monte Carlo:** 1. Fit return distribution (or use historical). 2. Simulate 10,000+ portfolio paths. 3. VaR = (1-α) percentile of simulated losses.

### Phase 3: Verification
Backtest: count how often actual losses exceed VaR over the past year. At 95% confidence, exceedances should be ~5%. Use Kupiec or Christoffersen test.
**Gate:** Backtest exceedance rate within acceptable bounds.

### Phase 4: Output
Return VaR estimate with backtest results.

## Output Format

```json
{
  "var": {"amount": 1250000, "confidence": 0.95, "horizon_days": 1, "currency": "TWD"},
  "cvar": {"amount": 1800000},
  "backtest": {"exceedances": 13, "expected": 12.5, "days_tested": 250, "pass": true},
  "metadata": {"method": "historical_simulation", "portfolio_value": 50000000}
}
```

## Examples

### Sample I/O
**Input:** Portfolio value = $1,000,000. Last 20 sorted daily returns (descending loss): 
```
[-0.050, -0.040, -0.035, -0.030, -0.025, -0.020, -0.015, -0.010, -0.005, 0.000,
  0.005,  0.010,  0.015,  0.020,  0.025,  0.030,  0.035,  0.040,  0.045,  0.050]
```
Confidence = 95%, horizon = 1 day.

**Expected (Historical Simulation):**
- 5th percentile index = floor(20 × 0.05) = 1 → return[1] = -0.040
- VaR = $1,000,000 × 0.040 = **$40,000**
- CVaR (Expected Shortfall) = mean of returns worse than VaR = (-0.050) × $1M = **$50,000**

Verify: VaR ≤ CVaR always (tail loss ≥ threshold loss). Count of losses > VaR should be ≤ 5% of observations (1 of 20).

### Edge Cases
| Input | Expected | Why |
|-------|----------|-----|
| Normal market conditions | VaR looks adequate | But misses tail events |
| 2008-like crisis in history | Higher VaR from historical method | Captures fat tails if crisis is in window |
| Very short history (30 days) | Unreliable VaR | Insufficient data for tail estimation |

## Gotchas

- **Normality assumption**: Parametric VaR assumes normal returns. Financial returns have fat tails — parametric VaR UNDERESTIMATES tail risk.
- **Historical window**: Historical simulation is only as good as the history. If the past 250 days were calm, VaR will be low even if a crisis is coming.
- **Time scaling**: VaR scales with √T only under independence and normality. For volatile or trending markets, this approximation is poor.
- **Diversification illusion**: VaR from correlated assets using normal-times correlations understates risk. Correlations spike during crises (correlation breakdown).
- **Gaming VaR**: Traders can structure positions that look safe under VaR but have catastrophic tail risk. This is why regulators also require stress testing.

## References

- For Expected Shortfall (CVaR) calculation, see `references/expected-shortfall.md`
- For VaR backtesting methods, see `references/backtesting.md`