← 返回 Skills 市场
gechengling

Security Portfolio Risk

作者 lingfeng-19 · GitHub ↗ · v2.0.0 · MIT-0
cross-platform ✓ 安全检测通过
82
总下载
1
收藏
0
当前安装
2
版本数
在 OpenClaw 中安装
/install security-portfolio-risk
功能描述
Provides AI-driven portfolio risk analysis for China A-shares with VaR, stress testing, tail risk, factor exposure, and risk attribution for fund managers.
使用说明 (SKILL.md)

\r \r

Portfolio Risk Analysis Expert / 组合风险分析专家\r

\r

English: AI-powered portfolio risk analysis expert — covers VaR calculation, stress testing, tail risk measurement, factor exposure, and risk attribution. Built for fund managers and risk analysts.\r \r 中文: 组合风险分析专家——覆盖VaR计算、压力测试、尾部风险度量、因子敞口分析、风险归因。适用:基金经理、风险分析师、机构投资者。\r \r ---\r \r

Industry Pain Points / 行业痛点\r

\r | Pain Point / 痛点 | Impact / 影响 | Solution / 本Skill解决方案 |\r |------------------|-------------|------------------------|\r | 系统风险难预测 | 黑天鹅事件导致大幅回撤 | 极端情景压力测试+尾部风险分析 |\r | 因子敞口不清晰 | 不知道组合暴露在哪些风险上 | 因子归因模型+敞口分解 |\r | 回撤控制困难 | 持有人体验差,资金赎回压力 | 动态回撤监控+预警机制 |\r | 相关性突变 | 平时低相关的资产大跌时齐跌 | 相关性压力测试+分散化效果评估 |\r | 合规要求高 | 资管新规净值化要求 | 标准风险指标+监管报告 |\r \r ---\r \r

Trigger Keywords / 触发关键词\r

\r English Triggers: portfolio risk, VaR, stress testing, risk decomposition, factor exposure, tail risk, risk attribution, China A-share, fund management, risk management\r \r 中文触发词(优先): 组合风险 / 风险分析 / VaR / 压力测试 / 回撤控制 / 风险归因 / 因子敞口 / 尾部风险 / 风险分解 / 风险预警 / 资产配置 / 分散化 / 相关性分析 / 最大回撤 / 夏普比率 / 波动率 / 风险调整收益 / 风险预算 / VaR计算 / CVaR / ES\r \r ---\r \r

Core Capabilities / 核心能力\r

\r

1. VaR & Risk Metrics / VaR与风险指标\r

\r

import numpy as np\r
import pandas as pd\r
from scipy import stats\r
\r
class PortfolioRiskAnalyzer:\r
    """组合风险分析引擎"""\r
    \r
    def __init__(self, returns: pd.DataFrame, weights: np.ndarray):\r
        """\r
        Args:\r
            returns: 收益率序列(列=资产,行=日期)\r
            weights: 资产权重向量\r
        """\r
        self.returns = returns\r
        self.weights = weights\r
        self.n_assets = len(weights)\r
    \r
    def calculate_var(self, confidence: float = 0.95, \r
                      method: str = "historical") -> dict:\r
        """计算VaR(Value at Risk)"""\r
        portfolio_returns = (self.returns * self.weights).sum(axis=1)\r
        \r
        if method == "historical":\r
            var = np.percentile(portfolio_returns, (1 - confidence) * 100)\r
        elif method == "parametric":\r
            mu = portfolio_returns.mean()\r
            sigma = portfolio_returns.std()\r
            var = stats.norm.ppf(1 - confidence, mu, sigma)\r
        elif method == "modified":\r
            # Cornish-Fisher调整\r
            mu = portfolio_returns.mean()\r
            sigma = portfolio_returns.std()\r
            skew = stats.skew(portfolio_returns)\r
            kurt = stats.kurtosis(portfolio_returns)\r
            z = stats.norm.ppf(1 - confidence)\r
            z_cf = (z + (z**2 - 1) * skew / 6 + \r
                   (z**3 - 3*z) * kurt / 24 - \r
                   (2*z**3 - 5*z) * skew**2 / 36)\r
            var = mu + sigma * z_cf\r
        \r
        return {\r
            "var": round(var * 100, 2),  # 百分比\r
            "var_amount": round(var * 1000000, 2),  # 假设100万组合\r
            "confidence": confidence,\r
            "method": method,\r
            "interpretation": f"在{confidence*100}%置信度下,最大损失为{abs(var)*100:.2f}%"\r
        }\r
    \r
    def calculate_cvar(self, confidence: float = 0.95) -> dict:\r
        """计算CVaR(Conditional VaR / Expected Shortfall)"""\r
        portfolio_returns = (self.returns * self.weights).sum(axis=1)\r
        var = np.percentile(portfolio_returns, (1 - confidence) * 100)\r
        \r
        cvar = portfolio_returns[portfolio_returns \x3C= var].mean()\r
        \r
        return {\r
            "cvar": round(cvar * 100, 2),\r
            "cvar_amount": round(cvar * 1000000, 2),\r
            "interpretation": f"超过VaR时的平均损失为{abs(cvar)*100:.2f}%"\r
        }\r
    \r
    def calculate_max_drawdown(self) -> dict:\r
        """计算最大回撤"""\r
        cumulative = (1 + self.returns @ self.weights).cumprod()\r
        running_max = cumulative.expanding().max()\r
        drawdown = (cumulative - running_max) / running_max\r
        \r
        max_dd = drawdown.min()\r
        max_dd_end = drawdown.idxmin()\r
        max_dd_start = cumulative[:max_dd_end].idxmax()\r
        \r
        return {\r
            "max_drawdown": round(max_dd * 100, 2),\r
            "peak_date": str(max_dd_start.date()),\r
            "trough_date": str(max_dd_end.date()),\r
            "recovery_date": None  # 需后续计算\r
        }\r
    \r
    def factor_risk_attribution(self, factor_returns: pd.DataFrame) -> dict:\r
        """因子风险归因"""\r
        portfolio_returns = self.returns @ self.weights\r
        \r
        # 回归分析\r
        X = factor_returns.values\r
        X = np.column_stack([np.ones(len(X)), X])\r
        y = portfolio_returns.values\r
        \r
        coeffs = np.linalg.lstsq(X, y, rcond=None)[0]\r
        residuals = y - X @ coeffs\r
        \r
        # 分解方差\r
        total_var = np.var(y)\r
        factor_var = np.var(X[:, 1:] @ coeffs[1:])\r
        specific_var = np.var(residuals)\r
        \r
        return {\r
            "factor_exposure": {\r
                "market": round(coeffs[1], 3),\r
                "factors": {\r
                    col: round(coef, 3) \r
                    for col, coef in zip(factor_returns.columns, coeffs[2:])\r
                }\r
            },\r
            "risk_contribution": {\r
                "factor_risk": round(factor_var / total_var * 100, 2),\r
                "specific_risk": round(specific_var / total_var * 100, 2)\r
            },\r
            "r_squared": round(1 - specific_var / total_var, 4)\r
        }\r
```\r
\r
### 2. Stress Testing / 压力测试\r
\r
```python\r
class StressTestScenarios:\r
    """压力测试情景库"""\r
    \r
    SCENARIOS = {\r
        "2015股灾重演": {\r
            "description": "假设上证指数单周下跌20%",\r
            "market_shock": -0.20,\r
            "sector_impacts": {\r
                "金融": -0.25,\r
                "房地产": -0.30,\r
                "消费": -0.15,\r
                "科技": -0.20,\r
                "医药": -0.10\r
            },\r
            "liquidity_shock": 0.5  # 流动性降至50%\r
        },\r
        \r
        "利率急升": {\r
            "description": "假设基准利率上调100bp",\r
            "rate_shock": 0.01,\r
            "bond_impact": -0.08,\r
            "equity_impact": -0.10,\r
            "bank_impact": -0.05\r
        },\r
        \r
        "人民币急贬": {\r
            "description": "假设USD/CNY一日升值5%",\r
            "fx_shock": 0.05,\r
            "export_related": -0.15,\r
            "import_related": 0.05,\r
            "domestic_consumer": -0.08\r
        },\r
        \r
        "黑天鹅-新冠": {\r
            "description": "类似2020年初疫情冲击",\r
            "market_shock": -0.12,\r
            "travel": -0.30,\r
            "retail": -0.20,\r
            "healthcare": 0.10,\r
            "online": 0.05\r
        }\r
    }\r
    \r
    def run_stress_test(self, portfolio: dict, scenario: str) -> dict:\r
        """执行压力测试"""\r
        if scenario not in self.SCENARIOS:\r
            raise ValueError(f"Unknown scenario: {scenario}")\r
        \r
        s = self.SCENARIOS[scenario]\r
        positions = portfolio["positions"]\r
        \r
        stressed_pnl = 0\r
        stressed_values = []\r
        \r
        for pos in positions:\r
            sector = pos.get("sector", "general")\r
            weight = pos["weight"]\r
            \r
            # 根据情景调整\r
            if "sector_impacts" in s and sector in s["sector_impacts"]:\r
                shock = s["sector_impacts"][sector]\r
            else:\r
                shock = s.get("market_shock", -0.10)\r
            \r
            pos_stressed = weight * (1 + shock)\r
            stressed_values.append(pos_stressed)\r
            stressed_pnl += weight * shock\r
        \r
        total_value = sum(stressed_values)\r
        portfolio_stress_loss = total_value - 1  # 假设初始为1\r
        \r
        return {\r
            "scenario": scenario,\r
            "description": s["description"],\r
            "portfolio_loss": round(portfolio_stress_loss * 100, 2),\r
            "portfolio_value_after": round(total_value * 100, 2),\r
            "position_impacts": [\r
                {"name": pos["name"], "weight": pos["weight"], \r
                 "shock": round(shock * 100, 2), "impact": "loss" if shock \x3C 0 else "gain"}\r
                for pos, shock in zip(positions, \r
                    [s.get("sector_impacts", {}).get(pos.get("sector", ""), \r
                     s.get("market_shock", -0.10)) for pos in positions])\r
            ]\r
        }\r
```\r
\r
### 3. Risk Contribution Analysis / 风险贡献分析\r
\r
```python\r
    def risk_contribution_by_asset(self) -> dict:\r
        """计算各资产风险贡献"""\r
        cov_matrix = self.returns.cov()\r
        portfolio_vol = np.sqrt(self.weights @ cov_matrix.values @ self.weights)\r
        \r
        # 边际风险贡献 (MCTR)\r
        mctr = (cov_matrix.values @ self.weights) / portfolio_vol\r
        \r
        # 风险贡献\r
        risk_contrib = self.weights * mctr\r
        \r
        return {\r
            "portfolio_volatility": round(portfolio_vol * 100, 2),\r
            "asset_risk_contribution": {\r
                self.returns.columns[i]: round(rc * 100, 2)\r
                for i, rc in enumerate(risk_contrib)\r
            },\r
            "concentration_risk": {\r
                "max_concentration": round(max(risk_contrib) * 100, 2),\r
                "diversification_benefit": round(\r
                    (sum([self.returns[col].std() * w \r
                         for col, w in zip(self.returns.columns, self.weights)]) - \r
                     portfolio_vol) * 100, 2)\r
            }\r
        }\r
```\r
\r
---\r
\r
## Quick Command Templates / 快速指令模板\r
\r
**组合风险评估:**\r
```\r
分析以下组合的风险:\r
- 总规模:1000万\r
- 持仓:[股票A 30%, 股票B 20%, 债券B 50%]\r
- 置信度:95%\r
```\r
\r
**压力测试:**\r
```\r
执行"2015股灾重演"情景压力测试\r
```\r
\r
---\r
\r
## Disclaimer\r
\r
This skill provides risk analysis tools for educational purposes. Risk metrics are based on historical data and statistical models, which do not guarantee future accuracy. Investment decisions should be made based on comprehensive analysis and professional advice.\r
安全使用建议
This appears safe to install from a security perspective based on the provided artifacts. Treat its portfolio analysis as decision support rather than guaranteed financial advice, validate assumptions and data independently, and note that the source/provenance information is limited.
功能分析
Type: OpenClaw Skill Name: security-portfolio-risk Version: 2.0.0 The skill bundle provides standard financial risk analysis tools, including VaR calculation, stress testing, and risk attribution using Python libraries like NumPy and Pandas. The code and instructions in SKILL.md are well-documented and align with the stated purpose of portfolio risk management without any indicators of malicious intent or suspicious behavior.
能力评估
Purpose & Capability
The visible SKILL.md content is coherent with the stated purpose: portfolio risk analysis, VaR/CVaR, stress testing, factor exposure, and risk attribution for China A-share portfolios.
Instruction Scope
The provided instructions do not attempt to override user intent, force tool use, request secrets, access accounts, or run commands automatically.
Install Mechanism
There is no install spec and no code files, which limits execution risk. However, the source/homepage are absent and the registry version differs from the SKILL.md frontmatter version.
Credentials
No required binaries, environment variables, credentials, config paths, network access, or local file access are declared. The included Python appears to be illustrative calculation logic rather than installed runtime code.
Persistence & Privilege
The artifacts show no persistence, background agents, privileged account access, credential use, or long-running autonomous behavior.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install security-portfolio-risk
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /security-portfolio-risk 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v2.0.0
Portfolio Risk Analysis Expert v2.0.0 - Expanded skill description and keyword set to better reflect Chinese market needs. - Improved clarity and searchability by adding more relevant keywords (e.g., 风险管理, 最大回撤, 夏普比率, 收益风险比, 资产配置, 风险预算). - No changes to functionality; update limited to documentation (SKILL.md).
v1.0.0
Initial release of Portfolio Risk Analysis Expert for China market. - Provides portfolio VaR calculation (historical, parametric, modified), CVaR/ES, maximum drawdown, and risk metrics. - Includes factor exposure analysis and risk attribution using regression against factor returns. - Offers extreme scenario-based stress testing, covering major China market risks (e.g., 2015 crash, interest rate spikes, currency moves, COVID-style shocks) with preset scenarios. - Designed specifically for fund managers, risk analysts, and institutional investors focusing on Chinese portfolios. - Supports both English and Chinese trigger keywords and explanations.
元数据
Slug security-portfolio-risk
版本 2.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 2
常见问题

Security Portfolio Risk 是什么?

Provides AI-driven portfolio risk analysis for China A-shares with VaR, stress testing, tail risk, factor exposure, and risk attribution for fund managers. 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 82 次。

如何安装 Security Portfolio Risk?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install security-portfolio-risk」即可一键安装,无需额外配置。

Security Portfolio Risk 是免费的吗?

是的,Security Portfolio Risk 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Security Portfolio Risk 支持哪些平台?

Security Portfolio Risk 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Security Portfolio Risk?

由 lingfeng-19(@gechengling)开发并维护,当前版本 v2.0.0。

💬 留言讨论