Communitygithub.com

MikeCheng1208/BattleTree

投资组合分配与再平衡优化器。管理股票/现金/债券之间的资产配置,根据市场状态和风险承受能力进行定期再平衡,确保多元化。

BattleTree 是什么?

BattleTree 是一个专业的投资组合管理代理技能,专为 AI 编码代理(如 Claude Code、Cursor、Codex 等)设计。它通过动态资产配置、定期再平衡和风险指标监控,帮助开发者或投资者优化投资组合的风险调整后收益。该技能支持根据市场状态(如 RISK_ON、RISK_OFF、TRANSITION)自动调整股票、债券和现金的目标分配比例,并基于阈值触发再平衡操作(偏差超过 5% 建议再平衡,超过 10% 则紧急再平衡)。它集成了市场状态检测器,使用 VIX、GDP 增长、失业率等宏观指标判断市场环境,并采用改良的凯利准则和现代投资组合理论(MPT)进行头寸规模优化。此外,它还包含行业多元化限制(如科技股最高 40%)、宪法合规性检查(例如第 4 条),并能与其他智能体(如 War Room)协作,在产生交易信号时确保整体投资组合平衡。输出格式为结构化的 JSON,包含当前分配、目标分配、偏差、再平衡交易清单以及风险分析等详细信息,非常适合需要自动化投资组合管理的金融科技应用。

兼容平台~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. 再平衡触发条件

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

示例:
目标: 股票 70%
当前: 股票 76%
偏差: +6% → 再平衡

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

3. 风险指标监控

  • 投资组合 Beta: 市场相对波动性
  • 夏普比率: 风险调整后收益
  • 最大回撤: 最大跌幅
  • 相关性矩阵: 资产间的相关性

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 > 阈值:
    → 生成再平衡交易
  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%

输出:
- 建议: 持有
- 原因: "偏差 < 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

与其他代理的协作

作战室 → 交易信号
  ↓
投资组合管理器 → 检查当前配置
  ↓
IF 新头寸导致失衡:
  → 建议部分头寸规模
  或者
  → 建议先卖出其他头寸

示例:
作战室: 买入 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.

相关技能