risk-modeling-guide

本条目面向金融投资分析场景,提供“risk-modeling-guide”技能的目录入口。公开标签:learning、VaR、压力测试、信用风险。请通过固定上游版本核对实际功能、依赖与权限;此页为 Skillπ 独立编写的用途介绍和原站链接,不代表运行安全保证。原文与附件依各自许可开放。

仓库
brycewang-stanford/Auto-Empirical-Research-Skills
仓库最近推送
Stars
5,023
Forks
578
Issues / PRs
0

安装方式

先用 Prompt 核对来源,也可切换到安装命令或下载可用的安装包。

安装方式

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "risk-modeling-guide":https://skillpi.com/zh/skills/deepskill-cfe71408d6cb4b1fda8372cf2a149fcfec2edf91fe1b1d6ce85831f034fb674f。安装前核对上游来源和版本:https://github.com/brycewang-stanford/Auto-Empirical-Research-Skills/blob/bfa0a6e5a843babbf45a1ef1663fd5dc4f07c0ba/skills/43-wentorai-research-plugins/skills/domains/finance/risk-modeling-guide/SKILL.md。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

此命令从 GitHub 来源仓库获取指定技能。运行前请先查看源文件。

运行工具
npx skills add https://github.com/brycewang-stanford/Auto-Empirical-Research-Skills/tree/bfa0a6e5a843babbf45a1ef1663fd5dc4f07c0ba/skills/43-wentorai-research-plugins/skills/domains/finance/risk-modeling-guide --skill risk-modeling-guide
许可协议: —

来源与配置

查看 GitHub 源码

brycewang-stanford/Auto-Empirical-Research-Skills固定提交 bfa0a6e5a843babbf45a1ef1663fd5dc4f07c0ba

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

本条目面向金融投资分析场景,提供“risk-modeling-guide”技能的目录入口。公开标签:learning、VaR、压力测试、信用风险。请通过固定上游版本核对实际功能、依赖与权限;此页为 Skillπ 独立编写的用途介绍和原站链接,不代表运行安全保证。原文与附件依各自许可开放。

↓ 0 下载 ↗ 0 分享点击

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
---
name: risk-modeling-guide
description: "Financial risk modeling including VaR, stress testing, and credit risk"
metadata:
  openclaw:
    emoji: "📉"
    category: "domains"
    subcategory: "finance"
    keywords: ["risk-modeling", "var", "stress-testing", "credit-risk", "monte-carlo", "basel"]
    source: "wentor"
---

# Risk Modeling Guide

A skill for quantitative financial risk modeling, covering Value at Risk, Expected Shortfall, credit risk, stress testing, and Monte Carlo simulation methods. Essential for financial engineering research and regulatory risk analysis.

## Market Risk: Value at Risk

### VaR Methodologies

| Method | Description | Pros | Cons |
|--------|-------------|------|------|
| Historical simulation | Replay past returns | No distributional assumption | Assumes past repeats |
| Variance-covariance | Assume normal returns | Fast, analytical | Underestimates tail risk |
| Monte Carlo simulation | Simulate from fitted model | Flexible distributions | Computationally expensive |
| Filtered historical simulation | GARCH + historical innovations | Captures volatility clustering | More complex |

### Implementation

```python
import numpy as np
import pandas as pd
from scipy.stats import norm, t as t_dist

def historical_var(returns: np.ndarray, confidence: float = 0.99,
                    horizon_days: int = 1) -> dict:
    """
    Compute Value at Risk using historical simulation.
    returns: array of daily log returns
    confidence: confidence level (e.g., 0.99 for 99% VaR)
    horizon_days: risk horizon in days
    """
    # Scale returns to horizon
    if horizon_days > 1:
        # Rolling sum for overlapping returns
        scaled_returns = pd.Series(returns).rolling(horizon_days).sum().dropna().values
    else:
        scaled_returns = returns

    alpha = 1 - confidence
    var = -np.percentile(scaled_returns, alpha * 100)
    es = -np.mean(scaled_returns[scaled_returns <= -var])

    return {
        "VaR": round(var, 6),
        "Expected_Shortfall": round(es, 6),
        "confidence": confidence,
        "horizon_days": horizon_days,
        "n_observations": len(scaled_returns),
    }

def parametric_var(returns: np.ndarray, confidence: float = 0.99,
                    distribution: str = "normal") -> dict:
    """
    Parametric VaR assuming normal or Student-t distribution.
    """
    mu = np.mean(returns)
    sigma = np.std(returns, ddof=1)

    if distribution == "normal":
        z = norm.ppf(1 - confidence)
        var = -(mu + sigma * z)
        # Analytical ES for normal
        es = -mu + sigma * norm.pdf(norm.ppf(1 - confidence)) / (1 - confidence)
    elif distribution == "student-t":
        # Fit Student-t
        df, loc, scale = t_dist.fit(returns)
        z = t_dist.ppf(1 - confidence, df)
        var = -(loc + scale * z)
        # ES for Student-t
        t_pdf = t_dist.pdf(t_dist.ppf(1 - confidence, df), df)
        es = -loc + scale * (t_pdf / (1 - confidence)) * ((df + z**2) / (df - 1))
    else:
        raise ValueError(f"Unknown distribution: {distribution}")

    return {
        "VaR": round(var, 6),
        "Expected_Shortfall": round(es, 6),
        "distribution": distribution,
        "mean": round(mu, 6),
        "std": round(sigma, 6),
    }
```

### Monte Carlo VaR

```python
def monte_carlo_var(returns: np.ndarray, n_simulations: int = 100000,
                     confidence: float = 0.99,
                     horizon_days: int = 10) -> dict:
    """
    Monte Carlo VaR using GBM (Geometric Brownian Motion).
    """
    mu = np.mean(returns)
    sigma = np.std(returns, ddof=1)

    # Simulate daily returns for the horizon
    rng = np.random.default_rng(42)
    simulated = rng.normal(
        mu * horizon_days,
        sigma * np.sqrt(horizon_days),
        size=n_simulations,
    )

    alpha = 1 - confidence
    var = -np.percentile(simulated, alpha * 100)
    es = -np.mean(simulated[simulated <= -var])

    return {
        "VaR": round(var, 6),
        "Expected_Shortfall": round(es, 6),
        "n_simulations": n_simulations,
        "confidence": confidence,
        "horizon_days": horizon_days,
    }
```

## Credit Risk Modeling

### Probability of Default Estimation

```python
from sklearn.linear_model import LogisticRegression

def build_pd_model(features: pd.DataFrame,
                    default_flag: pd.Series) -> dict:
    """
    Build a Probability of Default (PD) model using logistic regression.
    Common features: debt-to-income, credit utilization, payment history,
    employment length, loan amount.
    """
    model = LogisticRegression(max_iter=1000, class_weight="balanced")
    model.fit(features, default_flag)

    # Coefficient interpretation
    coef_df = pd.DataFrame({
        "feature": features.columns,
        "coefficient": model.coef_[0],
        "odds_ratio": np.exp(model.coef_[0]),
    }).sort_values("coefficient", ascending=False)

    # Model discrimination
    from sklearn.metrics import roc_auc_score
    pred_proba = model.predict_proba(features)[:, 1]
    auc = roc_auc_score(default_flag, pred_proba)

    return {
        "auc": round(auc, 4),
        "coefficients": coef_df.to_dict("records"),
        "intercept": round(model.intercept_[0], 4),
    }
```

### Loss Given Default and EAD

```python
def compute_expected_loss(pd_score: float, lgd: float,
                           ead: float) -> dict:
    """
    Compute Expected Loss = PD x LGD x EAD.
    pd_score: probability of default (0-1)
    lgd: loss given default (0-1, fraction of exposure lost)
    ead: exposure at default (dollar amount)
    """
    el = pd_score * lgd * ead
    return {
        "PD": pd_score,
        "LGD": lgd,
        "EAD": ead,
        "Expected_Loss": round(el, 2),
        "Unexpected_Loss_99": round(el * 2.33 * np.sqrt(pd_score * (1 - pd_score)), 2),
    }
```

## Stress Testing

### Scenario-Based Stress Tests

```python
def run_stress_test(portfolio_returns: pd.DataFrame,
                     scenarios: dict[str, dict]) -> pd.DataFrame:
    """
    Apply macroeconomic stress scenarios to a portfolio.
    scenarios: {name: {factor: shock_value}} where factors are
    macroeconomic variables (interest_rate, gdp_growth, unemployment, etc.)
    """
    # Factor sensitivities (betas from regression)
    # In practice, estimated via historical regression
    factor_betas = {
        "interest_rate": -0.15,    # portfolio loses 15bp per 1% rate increase
        "gdp_growth": 0.08,        # gains 8bp per 1% GDP growth
        "unemployment": -0.12,     # loses 12bp per 1% unemployment increase
        "equity_market": 0.45,     # 45bp per 1% equity market move
        "credit_spread": -0.25,    # loses 25bp per 1% spread widening
    }

    results = []
    for name, shocks in scenarios.items():
        portfolio_impact = 0
        for factor, shock in shocks.items():
            beta = factor_betas.get(factor, 0)
            portfolio_impact += beta * shock

        results.append({
            "scenario": name,
            "portfolio_impact_pct": round(portfolio_impact * 100, 2),
            "shocks": shocks,
        })

    return pd.DataFrame(results)

# Example scenarios
scenarios = {
    "Mild Recession": {
        "interest_rate": -0.5, "gdp_growth": -2.0,
        "unemployment": 2.0, "equity_market": -15.0,
        "credit_spread": 1.5,
    },
    "Severe Recession": {
        "interest_rate": -1.0, "gdp_growth": -5.0,
        "unemployment": 5.0, "equity_market": -40.0,
        "credit_spread": 4.0,
    },
    "Rate Shock": {
        "interest_rate": 3.0, "gdp_growth": -1.0,
        "unemployment": 1.0, "equity_market": -10.0,
        "credit_spread": 1.0,
    },
}
```

## Regulatory Framework

### Basel III Capital Requirements

| Risk Type | Measurement | Capital Charge |
|-----------|-------------|---------------|
| Market risk | FRTB (Fundamental Review of the Trading Book) | ES at 97.5%, stressed calibration |
| Credit risk | SA or IRB approach | PD, LGD, EAD based risk weights |
| Operational risk | Basic Indicator / Standardized | Business indicator x ILM |
| Liquidity risk | LCR and NSFR ratios | High-quality liquid assets buffer |

## Tools and Libraries

- **QuantLib (Python/C++)**: Derivatives pricing and risk analytics
- **riskfolio-lib**: Portfolio risk and optimization in Python
- **arch (Python)**: GARCH models for volatility estimation
- **pyfolio**: Portfolio performance and risk analysis
- **OpenGamma Strata**: Open-source market risk analytics (Java)
- **Moody's Analytics / Bloomberg PORT**: Commercial risk platforms

版本历史

  1. v2026.07 GitHub ↗
    原版更新说明

    ## Highlights - **First tagged release.** Every gate is green: `make check` (validate + 183 unit tests + eval-harness + numeric benchmarks), validate-catalog, quality-evals, and OpenSSF Scorecard on `main`. - **Rigor double loop at 13 method families.** Each family closes taxonomy tag → eval scenario (does the agent avoid the method's known traps?) → deterministic numeric benchmark (does it recover the true effect?). New this cycle: heterogeneous treatment effects (CATE) and quantile treatment effects (QTE). - **Paper-WorkFlow flagship at 29/29 executable rigor gates**, now merged to its `main` with a drift-gated README badge — the credibility artifact is checked by CI, so it can never silently go stale ([RIGOR.md](https://github.com/brycewang-stanford/Paper-WorkFlow/blob/main/RIGOR.md)). - **1,150 vendored skills / 69 collections**, all license-audited, security-scanned, tracked in a machine-readable catalog with CI-enforced freshness, and importable as a single whole-repo router skill. - **Hardened weekly upstream syncs**: synced trees must pass the full gate before merge; this cycle both sync PRs were verified, patched (StatsPAI's SkillOpt execution-gate card restored), and merged. - **First-party plugin marketplace** (Python / R / Stata empirical-analysis plugins + guide) shipped in the previous cycle, now under a tagged version. ## Known Follow-Ups - Ecosystem benchmark comparison (AERS vs econometrics agents on the shared benchmark suite) — [PLAN-2026-07 week 3](https://github.com/brycewang-stanford/Auto-Empirical-Research-Skills/blob/main/docs/PLAN-2026-07.md). - Decomposition (Oaxaca–Blinder) and shift-share (Bartik) method families (weeks 3–4). - GitHub Pages catalog site, README demo screenshots, five-language README consistency script (week 4). ## Catalog - Top-level collections: **69** - `SKILL.md` files: **1150** - Cataloged agent tools: **335** ([`tools/CATALOG.md`](../tools/CATALOG.md)) ## Methodological rigor - Method families in the coverage map: **13** ([`RIGOR_COVERAGE.md`](RIGOR_COVERAGE.md)) - Eval scenarios: **26** (138 rubric items, 122 auto-checkable) ([`../eval-harness/`](../eval-harness/README.md)) - Benchmark tasks: **13** (70 gold checks, 58 required) ([`../benchmark/`](../benchmark/README.md)) ### Method families (skills tagged) - `iv`: 27 - `rdd`: 25 - `panel-fe`: 19 - `staggered-did`: 17 - `bayesian`: 13 - `did`: 10 - `event-study`: 10 - `matching`: 10 - `synthetic-control`: 10 - `cate`: 8 - `dml`: 8 - `survival`: 3 - `quantile`: 2 ### Eval scenarios by category - `causal-identification`: 14 - `citation-hygiene`: 1 - `reproducibility`: 2 - `research-integrity`: 1 - `runtime-safety`: 1 - `statistical-validity`: 2 - `writing-compliance`: 3 - `writing-style`: 2 ## License buckets - AGPL-3.0: 1 - Apache-2.0: 1 - CC-BY-NC-4.0 (non-commercial): 1 - CC-BY-SA-4.0: 1 - CC-BY-SA-4.0 (repository default): 4 - GPL-3.0: 1 - MIT: 35 - MIT Non-Commercial: 1 - Mixed (per-skill; see folder): 2 - UNKNOWN - check upstream: 22 ## Quality gates - `make check` — catalog/provenance/audit/eval freshness, repo hygiene, Paper-WorkFlow gates, stdlib unit tests, eval-harness lint + graded smoke, and the strict numeric benchmark (reference-gold drift fails the build). - External links and OpenSSF Scorecard run on their scheduled workflows.

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分 100。前四项来自 DeepSkill 收录的质量报告。

场景价值92/100
评分依据

覆盖金融风控核心场景:VaR、压力测试、信用风险建模

触发精准95/100
评分依据

触发词完整覆盖六大核心概念

结构规范93/100
评分依据

四大模块结构清晰,逻辑递进

执行可靠88/100
评分依据

使用标准科学计算库,来源可靠

证据可验 (前四项均值)92/100
计算方式

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

risk · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。

来源与使用声明 SkillPi 的部分技能资料来自公开来源或创作者提交。第三方内容的权利归各自权利人所有。安装或运行前,请查看原站的许可、权限要求和使用风险。

来源与使用

请按详情页的作者、原始来源和许可证核对使用条件,运行前检查技能需要的权限。目录收录不等于已验证安装或安全性。