Communitygithub.com

MikeCheng1208/BattleTree

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

BattleTree 是什麼?

此技能為一個專業的投資組合管理代理(Portfolio Manager Agent),專注於資產配置、再平衡與風險監控。它會根據市場狀態(如 RISK_ON、RISK_OFF、TRANSITION)動態調整股票、債券與現金的比例,並在偏離目標配置超過 5% 時觸發再平衡建議,超過 10% 則要求緊急處理。代理不僅處理資產類別層級的配置,還包含產業分散(如科技類股上限 40%)、持倉規模限制(單一標的 15% 上限),並整合夏普比率、最大回撤等風險指標。輸出為結構化 JSON 格式,包含建議行動、交易明細、風險分析及下次審查日期,並可與市場狀態偵測器及憲法規則引擎(如 Article 4 合規檢查)協同運作。此技能支援 Python 實作,提供基於閾值的再平衡演算法與現代投資組合理論(MPT)的最佳化函式,適合用於量化交易、自動化資產管理或作為 AI 代理(如 Claude Code、Codex)的金融模組。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/MikeCheng1208/BattleTree/tree/HEAD/.agents/skills/portfolio-manager-agent

在你喜歡的 AI 中提問

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

說明文件

投資組合經理代理 - Portfolio Manager Agent

角色

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

核心能力

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%

2. 再平衡觸發條件

如果偏離 > 5%:
  → 建議再平衡

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

如果偏離 > 10%:
  → 緊急再平衡
  → 立即通知

3. 風險指標監控

  • 投資組合貝塔值:相對於市場的波動性
  • 夏普比率:風險調整後報酬
  • 最大回撤:最大跌幅
  • 相關性矩陣:標的間相關性

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 = |目前 - 目標|

步驟 5:再平衡決策
  如果偏離 > 閾值:
    → 生成再平衡交易
  否則:
    → 維持當前配置

步驟 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
- 國內生產毛額成長率: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%

輸出:
- 建議:維持
- 理由:「偏離 < 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

與其他代理協作

作戰室 → 交易訊號
  ↓
投資組合經理 → 檢查當前配置
  ↓
如果新持倉導致失衡:
  → 建議部分持倉規模
  或者
  → 建議先賣出其他持倉

範例:
作戰室:買入 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 12 individual skills — each has its own dedicated page.

MikeCheng1208/BattleTree

Index-based file discovery using ABOUTME headers. Use INSTEAD of grep or Explore agent when searching for files by purpose or feature. Faster and more accurate than scanning code. Invoke this skill when user asks "which files handle X", "where is Y implemented", or when you need to find files related to a feature or task.

MikeCheng1208/BattleTree

Factor modeling and portfolio construction (Markowitz, Black-Litterman, constraints, turnover).

MikeCheng1208/BattleTree

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

MikeCheng1208/BattleTree

Analyze the CustomGPT.ai Labs Innovation workbook and cost tracking data to surface portfolio-level insights, trends, and recommendations for where to focus Innovation efforts.

MikeCheng1208/BattleTree

Personal meta-skill for Arach. Use this as the entry point to understand arach's projects, conventions, and available skills. Activates on "arach's projects", "what does arach work on", or when working in any arach/* repo.

MikeCheng1208/BattleTree

High-converting landing pages. Copy + design + implementation. Triggers: landing page, conversion page.

MikeCheng1208/BattleTree

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios,...

MikeCheng1208/BattleTree

Automate Klipfolio tasks via Rube MCP (Composio). Always search tools first for current schemas.

MikeCheng1208/BattleTree

Minimalist, typography-focused portfolio design system inspired by neo-brutalist and Swiss design principles. Emphasizes bold typography, generous whitespace, monochromatic color schemes, and elegant simplicity for developer/designer portfolios.

MikeCheng1208/BattleTree

Optimize project portfolio selection under constraints using mathematical optimization

MikeCheng1208/BattleTree

Detect and explain risk drift in lending portfolios over time using vintage analysis, migration matrices, and concentration metrics. Use when monitoring portfolio credit quality trends, preparing board risk reports, conducting stress testing, or when risk metrics deviate from appetite thresholds.

MikeCheng1208/BattleTree

Build a GitHub portfolio that gets you hired — curate 3-5 polished projects, craft compelling READMEs, deploy live demos, tell a coherent story across your repos, and align everything to AI-native development roles. Use when preparing your GitHub for job searches, deciding what to pin, or auditing your public presence.

相關技能