mcpField
R
risk-portfolio-manager

risk-portfolio-manager

github.com/dreamineering其他855 次安装41 周前更新
代码仓库

关于 risk-portfolio-manager

risk-portfolio-manager 是用于加密资产交易的风险管理技能,位于信号生成与交易执行之间。它分析仓位规模、组合风险、再平衡和防御动作,并提供带置信度的建议。

主要功能

  1. 01按信号与风险调整仓位
  2. 02计算 VaR、CVaR 与夏普比率
  3. 03检测配置偏移并提出再平衡
  4. 04设置亏损限额与防御动作
  5. 05执行压力情景分析

适用场景

  1. 01根据市场状态和风险容忍度确定仓位
  2. 02检查组合 VaR 与资产相关性
  3. 03配置日亏损限额及止损动作
  4. 04评估市场冲击下的组合变化

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/dreamineering/meme-times --skill risk-portfolio-manager

安装后在 Claude Code 中输入/risk-portfolio-manager确认已加载。

详细介绍

风险投资组合管理器 - AI 驱动的风险控制

位于信号生成与交易执行之间的系统化风险管理层。采用数据驱动的方法优化仓位规模、管理投资组合风险并自动执行防御措施。

核心原则

仓位规模与风险管理决定长期生存能力。任何单笔交易都不应威胁投资组合。

激活触发条件

- “设置该仓位的规模” - “我的投资组合风险是多少?” - “重新平衡我的持仓” - “计算 VaR” - “我应该止盈吗?” - “设置风险限额” - “检查投资组合相关性” - “每日亏损限额” - 关键词:仓位规模、风险管理、投资组合、配置、回撤、VaR、夏普比率、重新平衡、止损、止盈、相关性、多元化

核心功能

1. 仓位规模引擎

<position_sizing> 规模计算方法:

interface PositionSizeRequest {
  signal_strength: number;    // 0-1 from meme-trader
  token_risk_score: number;   // 1-10 from rug detection
  current_portfolio: Portfolio;
  market_regime: 'bull' | 'bear' | 'sideways' | 'volatile';
  risk_tolerance: 'conservative' | 'moderate' | 'degen';
}

interface PositionSizeResult {
  recommended_size_pct: number;  // % of portfolio
  recommended_size_usd: number;
  max_allowed_size: number;
  reasoning: string[];
  risk_warnings: string[];
}

凯利准则(修正版):

Optimal Size = (Win Rate * Avg Win - (1 - Win Rate) * Avg Loss) / Avg Win
Adjusted Size = Kelly * Fractional Multiplier (0.25-0.5 for safety)

风险调整型规模矩阵:

风险承受度基础规模单个仓位上限相关敞口上限
保守型0.5-1%2%5%
稳健型1-2%4%10%
激进型2-5%10%25%

基于信号的调整:

Final Size = Base Size * Signal Strength * (1 - Token Risk / 20) * Market Multiplier

Where:
- Signal Strength: 0.5-1.5 (weak to strong)
- Token Risk: 1-10 (lower is safer)
- Market Multiplier: 0.5 (volatile) to 1.2 (trending)

输出格式:

POSITION SIZE RECOMMENDATION

Token: $MEME
Signal Strength: 8/10
Token Risk Score: 4/10
Market Regime: BULL

RECOMMENDED SIZE:
├─ Percentage: 2.3% of portfolio
├─ Amount: $460 (of $20,000 portfolio)
├─ Max Allowed: $800 (4% limit)
└─ Risk-Adjusted: WITHIN LIMITS

REASONING:
1. Strong signal (8/10) supports above-average sizing
2. Low-medium risk token (4/10) allows full allocation
3. Bull market regime permits aggressive sizing
4. No correlation with existing positions

WARNINGS:
- Consider scaling in (3 tranches) vs single entry
- Set stop-loss at -25% ($345 max loss)

</position_sizing>

2. 投资组合风险指标

<risk_metrics> 实时投资组合仪表板:

PORTFOLIO RISK DASHBOARD
═══════════════════════════════════════

POSITIONS (5 active):
Token      | Size    | PnL      | Risk  | Weight
$BONK      | $4,200  | +$840    | 5/10  | 21%
$MEME      | $3,100  | +$620    | 4/10  | 15.5%
$DOGE      | $2,800  | -$140    | 3/10  | 14%
$WIF       | $2,500  | +$1,250  | 6/10  | 12.5%
SOL        | $7,400  | +$2,220  | 2/10  | 37%
───────────────────────────────────────
TOTAL      | $20,000 | +$4,790  |       | 100%

RISK METRICS:
├─ Daily VaR (95%): -$1,240 (-6.2%)
├─ Max Drawdown (30d): -18.3%
├─ Current Drawdown: 0% (at ATH)
├─ Sharpe Ratio (30d): 2.14
├─ Sortino Ratio: 2.87
├─ Beta to SOL: 1.34

CORRELATION MATRIX:
        BONK   MEME   DOGE   WIF    SOL
BONK    1.00   0.82   0.71   0.78   0.65
MEME    0.82   1.00   0.68   0.85   0.61
DOGE    0.71   0.68   1.00   0.59   0.54
WIF     0.78   0.85   0.59   1.00   0.72
SOL     0.65   0.61   0.54   0.72   1.00

CONCENTRATION RISK:
├─ Top Position: 37% (SOL) - WITHIN LIMIT
├─ Top 3 Positions: 72.5% - HIGH
├─ Herfindahl Index: 0.23 - MODERATE
└─ Meme Exposure: 63% - HIGH

ALERTS:
⚠️ High correlation between MEME and WIF (0.85)
⚠️ Meme sector concentration above 50%

风险计算:

interface PortfolioRisk {
  // Value at Risk
  var_95: number;       // 95% confidence daily VaR
  var_99: number;       // 99% confidence daily VaR
  cvar_95: number;      // Conditional VaR (expected shortfall)

  // Performance Risk
  sharpe_ratio: number;
  sortino_ratio: number;
  max_drawdown: number;
  current_drawdown: number;

  // Correlation Risk
  avg_correlation: number;
  max_correlation: number;
  correlation_cluster: string[]; // Highly correlated groups

  // Concentration Risk
  herfindahl_index: number;
  top_position_pct: number;
  sector_concentrations: Record<string, number>;
}

function calculateVaR(
  positions: Position[],
  confidence: number = 0.95,
  horizon_days: number = 1
): number {
  // Historical VaR using past 30 days of returns
  const returns = getHistoricalReturns(positions, 30);
  const portfolio_returns = calculatePortfolioReturns(returns, positions);
  const sorted = portfolio_returns.sort((a, b) => a - b);
  const index = Math.floor((1 - confidence) * sorted.length);
  return sorted[index] * getPortfolioValue(positions) * Math.sqrt(horizon_days);
}

</risk_metrics>

3. 动态重新平衡
**重新平衡触发条件:** - 与目标配置的偏差 > 5% - 单个仓位 > 上限 - 仓位之间的相关性飙升至 > 0.9 - 行业集中度 > 阈值 - 每周定期审查

目标配置框架:

interface AllocationTarget {
  core_holdings: {
    SOL: { target: 30, min: 20, max: 50 };
    stablecoins: { target: 20, min: 10, max: 40 };
  };
  satellite_holdings: {
    memes: { target: 30, min: 0, max: 50 };
    defi: { target: 15, min: 0, max: 30 };
    other: { target: 5, min: 0, max: 15 };
  };
  rebalance_threshold: 5; // % drift to trigger
}

重新平衡输出:

REBALANCING RECOMMENDATION

Current vs Target Allocation:
Category     | Current | Target | Drift  | Action
SOL          | 37%     | 30%    | +7%    | SELL $1,400
Memes        | 63%     | 50%    | +13%   | SELL $2,600
Stables      | 0%      | 20%    | -20%   | BUY $4,000

SUGGESTED TRADES:
1. SELL 15% of BONK position ($630) → USDC
2. SELL 20% of WIF position ($500) → USDC
3. SELL 10% of SOL position ($740) → USDC
4. Keep MEME and DOGE positions
5. Convert sales to USDC stablecoin buffer

POST-REBALANCE PROJECTION:
├─ SOL: 31% (target: 30%)
├─ Memes: 48% (target: 50%)
├─ Stables: 21% (target: 20%)
└─ VaR Reduction: -18% (improved risk profile)
4. 自动防御措施

<defensive_actions> 熔断系统:

interface KillSwitchConfig {
  daily_loss_limit: number;      // % of portfolio
  weekly_loss_limit: number;     // % of portfolio
  position_loss_limit: number;   // % per position
  drawdown_limit: number;        // % from peak
  correlation_spike_action: 'alert' | 'reduce' | 'exit';
  auto_execute: boolean;
}

const defaultKillSwitch: KillSwitchConfig = {
  daily_loss_limit: 10,      // Halt new trades at -10% day
  weekly_loss_limit: 20,     // Halt all activity at -20% week
  position_loss_limit: 30,   // Auto-close position at -30%
  drawdown_limit: 25,        // Emergency mode at -25% from peak
  correlation_spike_action: 'alert',
  auto_execute: false,       // Require confirmation in Phase 1
};

触发后的操作:

触发条件操作严重程度
仓位 -25%止损警告MEDIUM
仓位 -30%自动平仓(若已启用)HIGH
每日 -10%暂停新交易HIGH
每周 -20%退出至稳定币CRITICAL
回撤 -25%紧急清仓CRITICAL
相关性 > 0.95减少一个仓位MEDIUM

警报输出:

🚨 RISK ALERT: DAILY LOSS LIMIT APPROACHING

Current Day PnL: -8.7% ($-1,740)
Daily Limit: -10% ($-2,000)
Buffer Remaining: $260

TRIGGERED ACTIONS:
1. ⏸️ New trade execution PAUSED
2. ⚠️ Review all open positions
3. 📊 Increased monitoring frequency

RECOMMENDED:
- Review worst performing position (WIF: -15%)
- Consider partial exit if trend continues
- DO NOT average down

Type RESUME to re-enable trading
Type EXIT_ALL to liquidate positions

</defensive_actions>

5. 情景分析

<scenario_analysis> 压力测试:

interface StressScenario {
  name: string;
  market_move: {
    sol: number;      // % change
    memes: number;    // % change vs SOL
    correlation_shift: number;
  };
  probability: number;
}

const stressScenarios: StressScenario[] = [
  {
    name: 'SOL -30% Flash Crash',
    market_move: { sol: -30, memes: -50, correlation_shift: 0.2 },
    probability: 0.05,
  },
  {
    name: 'Meme Rotation Out',
    market_move: { sol: 0, memes: -40, correlation_shift: -0.1 },
    probability: 0.10,
  },
  {
    name: 'Bull Run Continuation',
    market_move: { sol: 50, memes: 100, correlation_shift: 0 },
    probability: 0.15,
  },
  {
    name: 'Black Swan Event',
    market_move: { sol: -60, memes: -80, correlation_shift: 0.3 },
    probability: 0.01,
  },
];

压力测试输出:

STRESS TEST RESULTS

Current Portfolio Value: $20,000

SCENARIO                    | Portfolio Impact | Probability
SOL -30% Flash Crash        | -$7,200 (-36%)   | 5%
Meme Rotation Out           | -$5,040 (-25%)   | 10%
Bull Run Continuation       | +$14,600 (+73%)  | 15%
Black Swan Event            | -$12,400 (-62%)  | 1%

EXPECTED PORTFOLIO VALUE:
├─ Base Case: $20,000
├─ Expected (prob-weighted): $22,340 (+11.7%)
├─ Worst Case (99%): -$12,400 (-62%)
└─ VaR (95%, 30d): -$4,800 (-24%)

RISK ASSESSMENT:
⚠️ High sensitivity to meme rotation (-25% scenario)
⚠️ Black swan exposure significant (-62%)
✓ Positive expected value in base scenarios
✓ Bull case upside substantial (+73%)

RECOMMENDATION:
Consider hedging meme exposure with SOL puts or reducing
meme allocation by 10-15% to improve risk profile.

</scenario_analysis>

集成接口

**风险管理器接收自:** - **meme-trader**:信号强度、代币风险评分 - **meme-executor**:当前仓位、入场价格 - **flow-tracker**:巨鲸动向、流动性数据 - **data-orchestrator**:经过验证的价格数据、质量评分 - **llama-analyst**:协议基本面、TVL 趋势

风险管理器提供给:

  • meme-executor:获批的仓位规模、止损位
  • meme-trader:仓位限额、可用资金
  • 所有技能:投资组合状态、风险警报

CLI 用法

# Calculate position size
npx tsx .claude/skills/risk-portfolio-manager/scripts/position-sizer.ts \
  --signal 8 \
  --risk-score 4 \
  --portfolio-file ./portfolio.json \
  --risk-mode moderate

# Get portfolio risk metrics
npx tsx .claude/skills/risk-portfolio-manager/scripts/risk-metrics.ts \
  --portfolio-file ./portfolio.json \
  --include-correlation \
  --var-confidence 95

# Rebalancing recommendation
npx tsx .claude/skills/risk-portfolio-manager/scripts/rebalancer.ts \
  --portfolio-file ./portfolio.json \
  --target-allocation ./targets.json \
  --threshold 5

# Run stress tests
npx tsx .claude/skills/risk-portfolio-manager/scripts/stress-test.ts \
  --portfolio-file ./portfolio.json \
  --scenarios default \
  --output-format detailed

# Check kill switch status
npx tsx .claude/skills/risk-portfolio-manager/scripts/kill-switch.ts \
  --portfolio-file ./portfolio.json \
  --check-status

质量门槛

<validation_rules>

  • 仓位规模计算要求价格数据质量评分 >= 85%
  • VaR 计算要求至少 30 天的干净历史数据
  • 相关性矩阵要求价格数据时间同步
  • 所有建议均须包含置信度
  • 仓位规模计算前必须进行 Rug 检测 </validation_rules>

错误处理

<error_recovery>

  • 缺少价格数据:使用最近一次已知数据并发出过期警告
  • 计算错误:采用保守回退方案(最小规模)
  • 熔断开关冲突:安全优先(暂停 > 继续)
  • 数据质量不足:拒绝计算仓位规模,并请求刷新数据 </error_recovery>

<see_also>

  • references/risk-models.md - 数学公式
  • references/allocation-templates.md - 目标投资组合
  • scripts/position-sizer.ts - 仓位规模引擎
  • scripts/risk-metrics.ts - 风险计算
  • scripts/kill-switch.ts - 自动安全防护 </see_also>

评论

支持 Markdown