Communitygithub.com

majiayu000/claude-skill-registry

投資組合配置與再平衡最佳化工具。根據市場狀態與風險承受度,管理股票/現金/債券的資產配置,執行定期再平衡,並確保投資組合多元化。

claude-skill-registry 是什麼?

Portfolio Manager Agent 是一個專為 AI Agent(如 Claude Code、Cursor、Codex)設計的投資組合管理技能。它能夠根據市場狀態(如 RISK_ON、RISK_OFF、TRANSITION)動態調整資產配置(股票/債券/現金),並透過閾值觸發機制(5% 偏差建議再平衡,10% 偏差緊急再平衡)自動產生交易建議。此技能整合了修正版凱利公式與現代投資組合理論(MPT)來計算最佳倉位,同時監控投資組合 Beta、夏普比率、最大回撤等風險指標,並確保任何調整都符合憲法第 4 條的合規限制。它還能與 War Room 等其他 Agent 協作,當新增部位可能導致失衡時,建議部分建倉或優先賣出其他部位。使用者可透過 JSON 格式的輸出取得當前與目標配置、偏差分析、再平衡交易清單及風險評估。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/majiayu000/claude-skill-registry/tree/HEAD/skills/agent/portfolio-manager-agent

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

投資組合經理 Agent - Portfolio Manager

職責

管理投資組合的資產配置、再平衡與多元化,以優化風險調整後報酬。

核心能力

1. 資產配置策略

根據市場狀態動態配置

# RISK_ON (經濟擴張,VIX < 20)
allocation = {
    'stocks': 0.70,
    'bonds': 0.20,
    'cash': 0.10
}

# RISK_OFF (經濟收縮,VIX > 25)
allocation = {
    'stocks': 0.40,
    'bonds': 0.40,
    'cash': 0.20
}

# TRANSITION (轉換期,VIX 20-25)
allocation = {
    'stocks': 0.55,
    'bonds': 0.30,
    'cash': 0.15
}

行業分散

科技股:最高 40%
金融股:最高 30%
醫療保健:最高 25%
其他行業:最高 20% each

2. 再平衡觸發條件

IF 偏差 > 5%:
  → 建議再平衡

範例:
目標:股票 70%
目前:股票 76%
偏差:+6% → 再平衡

IF 偏差 > 10%:
  → 緊急再平衡
  → 立即通知

3. 風險指標監控

  • Portfolio Beta:與市場相比的波動性
  • Sharpe Ratio:風險調整後報酬
  • Max Drawdown:最大回撤幅度
  • Correlation Matrix:資產之間相關性

4. 部位規模

# 修正版凱利公式
position_size = (win_rate * avg_win - (1 - win_rate) * avg_loss) / avg_win

# 部位限制
position_size = min(position_size, MAX_SINGLE_POSITION)  # 15%

決策框架

第1步:分析當前投資組合
  - 當前配置
  - 個別部位
  - 行業分布
  - 風險指標

第2步:偵測市場狀態
  from backend.ai.market_regime import MarketRegimeDetector
  regime = detector.detect_regime(market_data)

第3步:決定目標配置
  根據狀態:
    - RISK_ON → 積極 (70/20/10)
    - RISK_OFF → 保守 (40/40/20)
    - TRANSITION → 平衡 (55/30/15)

第4步:計算偏差
  deviation = |current - target|

第5步:再平衡決策
  IF deviation > threshold:
    → 產生再平衡交易
  ELSE:
    → 維持當前配置

第6步:套用憲法限制
  - 檢查第 4 條合規性
  - 確保部位限制
  - 驗證行業限制

輸出格式

{
  "agent": "portfolio_manager",
  "recommendation": "REBALANCE|HOLD",
  "confidence": 0.85,
  "reasoning": "市場狀態轉為 RISK_OFF,需減少股票比重",
  "current_allocation": {
    "stocks": 0.76,
    "bonds": 0.18,
    "cash": 0.06,
    "total_value_usd": 100000
  },
  "target_allocation": {
    "stocks": 0.55,
    "bonds": 0.30,
    "cash": 0.15
  },
  "deviation": {
    "stocks": 0.21,
    "bonds": -0.12,
    "cash": -0.09,
    "max_deviation": 0.21
  },
  "rebalancing_trades": [
    {
      "action": "SELL",
      "asset_class": "stocks",
      "amount_usd": 21000,
      "reason": "股票比重 76% → 55% 調整"
    },
    {
      "action": "BUY",
      "asset_class": "bonds",
      "amount_usd": 12000,
      "reason": "債券比重 18% → 30% 增加"
    },
    {
      "action": "INCREASE",
      "asset_class": "cash",
      "amount_usd": 9000,
      "reason": "現金比重增加(防禦性部位)"
    }
  ],
  "risk_analysis": {
    "portfolio_beta": 1.15,
    "sharpe_ratio": 1.45,
    "max_drawdown": -0.08,
    "expected_volatility": 0.18
  },
  "sector_breakdown": {
    "Technology": 0.35,
    "Finance": 0.20,
    "Healthcare": 0.15,
    "Other": 0.30
  },
  "next_review_date": "2025-12-28"
}

範例

範例 1:RISK_ON → 積極配置

輸入:
- VIX:15
- GDP 成長率:3.0%
- 市場狀態:RISK_ON
- 當前:股票 55%,債券 30%,現金 15%

輸出:
- 建議:再平衡
- 目標:股票 70%,債券 20%,現金 10%
- 交易:
  * 買入股票 $15,000
  * 賣出債券 $10,000
  * 減少現金 $5,000

範例 2:RISK_OFF → 防禦配置

輸入:
- VIX:28
- 衰退訊號
- 市場狀態:RISK_OFF
- 當前:股票 70%,債券 20%,現金 10%

輸出:
- 建議:緊急再平衡
- 目標:股票 40%,債券 40%,現金 20%
- 交易:
  * 賣出股票 $30,000
  * 買入債券 $20,000
  * 增加現金 $10,000

範例 3:偏差小 → 維持

輸入:
- 當前:股票 68%,債券 22%,現金 10%
- 目標:股票 70%,債券 20%,現金 10%
- 偏差:2%,2%,0%

輸出:
- 建議:HOLD
- 理由:「偏差 < 5%,考量交易成本,維持現狀較有利」

範例 4:行業再平衡

輸入:
- 科技股:45%(最高 40%)
- 金融股:15%
- 醫療保健:10%

輸出:
- 建議:行業再平衡
- 交易:
  * 賣出科技股 $5,000(45% → 40%)
  * 買入醫療保健 $3,000
  * 買入金融股 $2,000

準則

應做的事 ✅

  • 定期檢視:每週或隔週檢查
  • 市場狀態優先:根據總體環境配置
  • 漸進式再平衡:避免劇烈變化
  • 稅務效率:稅務高效的再平衡

不應做的事 ❌

  • 避免過度交易(考慮交易成本)
  • 避免對短期波動過度反應
  • 避免情緒化配置變動
  • 禁止違反憲法第 4 條

與市場狀態偵測器整合

from backend.ai.market_regime import MarketRegimeDetector
from backend.ai.regime_detector import detect_market_regime

detector = MarketRegimeDetector()

regime_data = {
    'vix': 18,
    'yield_curve_10y2y': 0.3,
    'fed_stance': 'neutral',
    'gdp_growth': 0.025,
    'unemployment': 0.038,
    'cpi': 0.028
}

regime = detector.detect_regime(regime_data)

# 輸出:
# {
#   "current_regime": "RISK_ON",
#   "confidence": 0.75,
#   "recommended_asset_allocation": {
#     "stocks": 0.70,
#     "bonds": 0.20,
#     "cash": 0.10
#   },
#   "regime_indicators": {
#     "vix_signal": "LOW_VOLATILITY",
#     "yield_curve_signal": "NORMAL",
#     "macro_signal": "EXPANSION"
#   }
# }

再平衡演算法

閾值式再平衡

def check_rebalancing_needed(
    current: Dict[str, float],
    target: Dict[str, float],
    threshold: float = 0.05
) -> bool:
    """檢查是否需要再平衡"""
    
    for asset_class in target.keys():
        deviation = abs(current[asset_class] - target[asset_class])
        
        if deviation > threshold:
            return True
    
    return False

# 範例
current = {'stocks': 0.76, 'bonds': 0.18, 'cash': 0.06}
target = {'stocks': 0.70, 'bonds': 0.20, 'cash': 0.10}

needs_rebalance = check_rebalancing_needed(current, target)  # True

最佳交易計算

def calculate_rebalancing_trades(
    current_allocation: Dict[str, float],
    target_allocation: Dict[str, float],
    total_portfolio_value: float
) -> List[Dict]:
    """計算再平衡所需的最佳交易"""
    
    trades = []
    
    for asset_class, target_pct in target_allocation.items():
        current_pct = current_allocation[asset_class]
        current_value = current_pct * total_portfolio_value
        target_value = target_pct * total_portfolio_value
        
        diff = target_value - current_value
        
        if abs(diff) > 1000:  # 最小交易金額 $1,000
            action = "BUY" if diff > 0 else "SELL"
            trades.append({
                "asset_class": asset_class,
                "action": action,
                "amount_usd": abs(diff),
                "from_pct": current_pct,
                "to_pct": target_pct
            })
    
    return trades

績效指標

  • 再平衡頻率:目標每月 1-2 次
  • 交易成本:低於投資組合價值的 0.5%
  • 夏普比率提升:目標相較於買入持有提升 +10%
  • 回撤降低:目標相較於未管理投資組合降低 -20%

憲法合規

from backend.constitution import Constitution

constitution = Constitution()

# 驗證再平衡交易
for trade in rebalancing_trades:
    # 檢查新配置是否違反第 4 條
    new_allocation = apply_trade(current_allocation, trade)
    
    is_valid, violations, _ = constitution.validate_allocation(
        new_allocation,
        current_positions
    )
    
    if not is_valid:
        # 調整交易以符合規定
        trade = adjust_trade_for_compliance(trade, violations)

風險調整後部位規模

現代投資組合理論 (MPT) 整合

import numpy as np
from scipy.optimize import minimize

def optimize_portfolio(
    returns: np.array,
    covariance: np.array,
    risk_free_rate: float = 0.03
) -> np.array:
    """使用 MPT 最佳化投資組合"""
    
    n_assets = len(returns)
    
    # 目標:最大化夏普比率
    def objective(weights):
        portfolio_return = np.dot(weights, returns)
        portfolio_std = np.sqrt(np.dot(weights, np.dot(covariance, weights)))
        sharpe = (portfolio_return - risk_free_rate) / portfolio_std
        return -sharpe  # 最小化負的夏普比率
    
    # 限制條件
    constraints = [
        {'type': 'eq', 'fun': lambda w: np.sum(w) - 1},  # 權重總和為 1
        {'type': 'ineq', 'fun': lambda w: w}  # 非負權重
    ]
    
    # 範圍(每檔股票最高 15%)
    bounds = tuple((0, 0.15) for _ in range(n_assets))
    
    # 初始猜測
    x0 = np.array([1/n_assets] * n_assets)
    
    # 最佳化
    result = minimize(objective, x0, method='SLSQP', bounds=bounds, constraints=constraints)
    
    return result.x

與其他 Agent 協作

War Room → 交易訊號
  ↓
投資組合經理 → 檢查當前配置
  ↓
若新部位導致失衡:
  → 建議部分建倉
  或
  → 建議優先賣出其他部位

範例:
War Room:買入 AAPL $15,000
投資組合經理:「科技股已達 38%,僅買入 $10,000」

報表

每週投資組合報告

# 投資組合績效報告 - 2025-12-21 當週

## 資產配置
- 股票:68%(目標:70%)✓
- 債券:22%(目標:20%)⚠️
- 現金:10%(目標:10%)✓

## 績效
- 週報酬:+2.3%
- 年初至今報酬:+15.7%
- 夏普比率:1.45
- 最大回撤:-8.2%

## 執行動作
- 無(在容許範圍內)

## 下次檢視日期:2025-12-28

版本歷史

  • v1.0 (2025-12-21):初始版本,包含 MPT 最佳化與市場狀態整合

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

majiayu000/claude-skill-registry

Builds, edit or validate Agent Skill through conversational discovery. Use when the user requests to "Create an Agent", "Optimize an Agent" or "Edit an Agent".

majiayu000/claude-skill-registry

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry

Analyzes current state and user query to answer BMad questions or recommend the next workflow or agent. Use when user says what should I do next, what do I do now, or asks a question about BMad

majiayu000/claude-skill-registry

Build AI agents with Google ADK Python (Agent Development Kit). Use for multi-agent systems, workflow agents (sequential/parallel/loop), Vertex AI deployment, tool integration, human-in-the-loop.

majiayu000/claude-skill-registry

Build AI agents with Google ADK Python (Agent Development Kit). Use for multi-agent systems, workflow agents (sequential/parallel/loop), Vertex AI deployment, tool integration, human-in-the-loop.

majiayu000/claude-skill-registry

Create a hilarious and ultra-realistic video of an anthropomorphic animal acting like a human vlogger in a real-world setting.

majiayu000/claude-skill-registry

Speech-to-text transcription and translation via OpenAI Audio API -- models, response formats, timestamps, prompting, streaming, chunking, and diarization

majiayu000/claude-skill-registry

BlockRun works with Claude Code and Google Antigravity.

majiayu000/claude-skill-registry

This skill should be used when the user asks about libraries, frameworks, API references, or needs code examples. Activates for setup questions, code generation involving libraries, or mentions of specific frameworks like React, Vue, Next.js, Prisma, Supabase, etc.

majiayu000/claude-skill-registry

小省导购员数字人带货版即梦视频提示词生成系统,基于四大智能体协同(提示词生成师、质量管控师、知识库运维师、跨环节适配师),按照"主体+运动+场景+(镜头语言+光影+氛围)"公式输出中英文双版提示词,适配5s短视频。确保人物一致性、视觉连贯性、情绪连贯性,支持知识库智能复用和跨工具适配(Suno音乐、AI绘画),为数字人带货视频提供高质量提示词生成服务。

majiayu000/claude-skill-registry

Upload and manage files using Google Gemini File API via scripts/. Use for uploading images, audio, video, PDFs, and other files for use with Gemini models. Supports file upload, status checking, and file management. Triggers on "upload file", "file API", "upload image", "upload PDF", "upload video", "file management".

majiayu000/claude-skill-registry

CRITICAL: Use for MolyKit AI chat toolkit. Triggers on: BotClient, OpenAI, SSE streaming, AI chat, molykit, PlatformSend, spawn(), ThreadToken, cross-platform async, Chat widget, Messages, PromptInput, Avatar, LLM

majiayu000/claude-skill-registry

AI and machine learning workflow covering LLM application development, RAG implementation, agent architecture, ML pipelines, and AI-powered features.

majiayu000/claude-skill-registry

Analyze images/audio/video with Gemini API (better vision than Claude). Generate images (Imagen 4), videos (Veo 3). Use for vision analysis, transcription, OCR, design extraction, multimodal AI.

majiayu000/claude-skill-registry

Analyze images/audio/video with Gemini API (better vision than Claude). Generate images (Imagen 4), videos (Veo 3). Use for vision analysis, transcription, OCR, design extraction, multimodal AI.

majiayu000/claude-skill-registry

Conduct domain and industry research. Use when the user says "lets create a research report on [domain or industry]

majiayu000/claude-skill-registry

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

相關技能