Communitygithub.com

majiayu000/claude-skill-registry

多專案組合分析儀表板。匯總多個專案的關鍵績效指標,追蹤組合健康狀況,比較績效,並支援高階決策。

claude-skill-registry 是什麼?

此技能提供一個全面的多專案組合分析儀表板,專為建築或工程專案管理設計。它允許使用者匯總和分析來自多個專案的數據,提供組合層級的能見度。該技能可追蹤關鍵績效指標(KPI),如成本績效指數 (CPI)、進度績效指數 (SPI)、安全指標 (TRIR) 和風險評分,並判定每個專案的整體健康狀態(綠色/黃色/紅色/灰色)。它能產生組合摘要、比較專案績效、識別高風險專案,並預測未來現金需求。該工具支援 Claude Code、Cursor 和 Codex 等平台,並以 Python 資料類別和強大的分析方法實作,使其成為高階主管和專案經理進行策略資源分配的強大決策支援系統。

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

在你喜歡的 AI 中提問

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

說明文件

專案組合儀表板

概述

匯總並分析跨多個建築專案的數據,以獲得組合層級的能見度。追蹤 KPI、識別趨勢、比較專案績效,並支援策略性資源分配決策。

組合分析框架

┌─────────────────────────────────────────────────────────────────┐
│                  專案組合儀表板                                  │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  專案 A       專案 B       專案 C       專案 D                  │
│     ↓             ↓            ↓            ↓                   │
│  ┌─────────────────────────────────────────────┐                │
│  │           數據匯總                            │                │
│  │  成本 | 進度 | 安全 | 品質 | 風險            │                │
│  └─────────────────────────────────────────────┘                │
│                         ↓                                        │
│  ┌─────────────────────────────────────────────┐                │
│  │          組合 KPI                            │                │
│  │  📊 總價值    📈 準時完成率 %                │
│  │  💰 預算內 %    🛡️ 安全率                    │
│  │  ⚠️ 風險評分     📋 資源利用率               │
│  └─────────────────────────────────────────────┘                │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

技術實作

from dataclasses import dataclass, field
from typing import List, Dict, Optional, Tuple
from datetime import datetime, timedelta
from enum import Enum
import statistics

class ProjectStatus(Enum):
    PLANNING = "planning"
    ACTIVE = "active"
    ON_HOLD = "on_hold"
    COMPLETE = "complete"
    CANCELLED = "cancelled"

class HealthStatus(Enum):
    GREEN = "green"       # 進度正常
    YELLOW = "yellow"     # 有風險
    RED = "red"           # 狀況危急
    GREY = "grey"         # 未開始/暫停

@dataclass
class ProjectMetrics:
    project_id: str
    project_name: str
    status: ProjectStatus
    contract_value: float
    percent_complete: float

    # 進度
    planned_start: datetime
    planned_end: datetime
    actual_start: Optional[datetime]
    forecast_end: datetime
    schedule_variance_days: int = 0

    # 成本
    budget: float
    actual_cost: float
    forecast_cost: float
    cost_variance: float = 0.0
    cpi: float = 1.0
    spi: float = 1.0

    # 安全
    recordable_incidents: int = 0
    total_hours: float = 0
    trir: float = 0.0

    # 品質
    defects_open: int = 0
    rework_cost: float = 0.0

    # 風險
    risk_score: float = 0.0
    critical_risks: int = 0

    @property
    def health(self) -> HealthStatus:
        """決定整體專案健康狀態。"""
        if self.status in [ProjectStatus.ON_HOLD, ProjectStatus.CANCELLED]:
            return HealthStatus.GREY

        # 若明顯超出預算/進度則為危急
        if self.cpi < 0.85 or self.spi < 0.85 or self.critical_risks > 3:
            return HealthStatus.RED

        # 若中度偏離則有風險
        if self.cpi < 0.95 or self.spi < 0.95 or self.critical_risks > 0:
            return HealthStatus.YELLOW

        return HealthStatus.GREEN

@dataclass
class PortfolioSummary:
    report_date: datetime
    total_projects: int
    active_projects: int
    total_contract_value: float
    total_budget: float
    total_actual_cost: float
    total_forecast_cost: float

    # 績效
    avg_cpi: float
    avg_spi: float
    on_budget_pct: float
    on_schedule_pct: float

    # 安全
    portfolio_trir: float
    total_incidents: int

    # 健康分布
    green_count: int
    yellow_count: int
    red_count: int

    # 趨勢
    cost_trend: str
    schedule_trend: str

@dataclass
class ProjectComparison:
    metric: str
    projects: Dict[str, float]
    avg: float
    best: Tuple[str, float]
    worst: Tuple[str, float]

class PortfolioDashboard:
    """多專案組合分析。"""

    # 健康狀態門檻
    THRESHOLDS = {
        "cpi_warning": 0.95,
        "cpi_critical": 0.85,
        "spi_warning": 0.95,
        "spi_critical": 0.85,
        "trir_warning": 2.0,
        "risk_score_warning": 7.0
    }

    def __init__(self, portfolio_name: str):
        self.portfolio_name = portfolio_name
        self.projects: Dict[str, ProjectMetrics] = {}
        self.snapshots: List[Dict] = []  # 歷史數據

    def add_project(self, metrics: ProjectMetrics):
        """在組合中新增或更新專案。"""
        self.projects[metrics.project_id] = metrics

    def import_projects(self, projects_data: List[Dict]) -> int:
        """從數據匯入多個專案。"""
        count = 0
        for p in projects_data:
            metrics = ProjectMetrics(
                project_id=p['id'],
                project_name=p['name'],
                status=ProjectStatus(p.get('status', 'active')),
                contract_value=p['contract_value'],
                percent_complete=p.get('percent_complete', 0),
                planned_start=p['planned_start'],
                planned_end=p['planned_end'],
                actual_start=p.get('actual_start'),
                forecast_end=p.get('forecast_end', p['planned_end']),
                budget=p['budget'],
                actual_cost=p.get('actual_cost', 0),
                forecast_cost=p.get('forecast_cost', p['budget']),
                cpi=p.get('cpi', 1.0),
                spi=p.get('spi', 1.0),
                recordable_incidents=p.get('incidents', 0),
                total_hours=p.get('total_hours', 0),
                risk_score=p.get('risk_score', 0),
                critical_risks=p.get('critical_risks', 0)
            )

            # 計算衍生指標
            metrics.cost_variance = metrics.budget - metrics.actual_cost
            metrics.schedule_variance_days = (metrics.planned_end - metrics.forecast_end).days

            if metrics.total_hours > 0:
                metrics.trir = (metrics.recordable_incidents * 200000) / metrics.total_hours

            self.add_project(metrics)
            count += 1

        return count

    def get_active_projects(self) -> List[ProjectMetrics]:
        """取得進行中專案清單。"""
        return [p for p in self.projects.values()
                if p.status == ProjectStatus.ACTIVE]

    def calculate_portfolio_summary(self) -> PortfolioSummary:
        """計算組合層級的摘要指標。"""
        active = self.get_active_projects()
        all_projects = list(self.projects.values())

        if not all_projects:
            return None

        # 總計
        total_contract = sum(p.contract_value for p in all_projects)
        total_budget = sum(p.budget for p in all_projects)
        total_actual = sum(p.actual_cost for p in all_projects)
        total_forecast = sum(p.forecast_cost for p in all_projects)

        # 績效平均值(按預算加權)
        if total_budget > 0:
            avg_cpi = sum(p.cpi * p.budget for p in active) / sum(p.budget for p in active) if active else 1.0
            avg_spi = sum(p.spi * p.budget for p in active) / sum(p.budget for p in active) if active else 1.0
        else:
            avg_cpi = avg_spi = 1.0

        # 預算內/準時完成百分比
        on_budget = len([p for p in active if p.cpi >= 0.95])
        on_schedule = len([p for p in active if p.spi >= 0.95])

        on_budget_pct = (on_budget / len(active) * 100) if active else 100
        on_schedule_pct = (on_schedule / len(active) * 100) if active else 100

        # 安全指標
        total_incidents = sum(p.recordable_incidents for p in all_projects)
        total_hours = sum(p.total_hours for p in all_projects)
        portfolio_trir = (total_incidents * 200000 / total_hours) if total_hours > 0 else 0

        # 健康分布
        green = len([p for p in active if p.health == HealthStatus.GREEN])
        yellow = len([p for p in active if p.health == HealthStatus.YELLOW])
        red = len([p for p in active if p.health == HealthStatus.RED])

        # 趨勢(若可取得前次快照則進行比較)
        cost_trend = "穩定"
        schedule_trend = "穩定"

        if self.snapshots:
            prev = self.snapshots[-1]
            if avg_cpi > prev.get('avg_cpi', 1.0):
                cost_trend = "改善中"
            elif avg_cpi < prev.get('avg_cpi', 1.0):
                cost_trend = "惡化中"

            if avg_spi > prev.get('avg_spi', 1.0):
                schedule_trend = "改善中"
            elif avg_spi < prev.get('avg_spi', 1.0):
                schedule_trend = "惡化中"

        return PortfolioSummary(
            report_date=datetime.now(),
            total_projects=len(all_projects),
            active_projects=len(active),
            total_contract_value=total_contract,
            total_budget=total_budget,
            total_actual_cost=total_actual,
            total_forecast_cost=total_forecast,
            avg_cpi=avg_cpi,
            avg_spi=avg_spi,
            on_budget_pct=on_budget_pct,
            on_schedule_pct=on_schedule_pct,
            portfolio_trir=portfolio_trir,
            total_incidents=total_incidents,
            green_count=green,
            yellow_count=yellow,
            red_count=red,
            cost_trend=cost_trend,
            schedule_trend=schedule_trend
        )

    def compare_projects(self, metric: str) -> ProjectComparison:
        """依特定指標比較專案。"""
        active = self.get_active_projects()

        if not active:
            return None

        metric_map = {
            "cpi": lambda p: p.cpi,
            "spi": lambda p: p.spi,
            "percent_complete": lambda p: p.percent_complete,
            "cost_variance": lambda p: p.cost_variance,
            "trir": lambda p: p.trir,
            "risk_score": lambda p: p.risk_score
        }

        if metric not in metric_map:
            raise ValueError(f"未知的指標: {metric}")

        getter = metric_map[metric]
        values = {p.project_name: getter(p) for p in active}

        avg = statistics.mean(values.values())

        # 最佳/最差取決於指標(CPI高好,TRIR低好)
        if metric in ["trir", "risk_score"]:
            best = min(values.items(), key=lambda x: x[1])
            worst = max(values.items(), key=lambda x: x[1])
        else:
            best = max(values.items(), key=lambda x: x[1])
            worst = min(values.items(), key=lambda x: x[1])

        return ProjectComparison(
            metric=metric,
            projects=values,
            avg=avg,
            best=best,
            worst=worst
        )

    def get_projects_at_risk(self) -> List[ProjectMetrics]:
        """取得需要注意的專案。"""
        return [p for p in self.get_active_projects()
                if p.health in [HealthStatus.YELLOW, HealthStatus.RED]]

    def get_top_risks(self, limit: int = 10) -> List[Dict]:
        """取得整個組合中最重要的風險。"""
        risks = []

        for p in self.get_active_projects():
            if p.risk_score > 0:
                risks.append({
                    "project": p.project_name,
                    "risk_score": p.risk_score,
                    "critical_risks": p.critical_risks,
                    "cpi": p.cpi,
                    "spi": p.spi
                })

        return sorted(risks, key=lambda x: -x['risk_score'])[:limit]

    def forecast_cash_needs(self, months: int = 6) -> List[Dict]:
        """預測整個組合的現金需求。"""
        forecasts = []

        for month in range(1, months + 1):
            month_date = datetime.now() + timedelta(days=month * 30)

            month_spend = 0
            for p in self.get_active_projects():
                # 根據剩餘工作進行簡單線性預測
                remaining = p.forecast_cost - p.actual_cost
                months_remaining = max(1, (p.forecast_end - datetime.now()).days / 30)
                monthly_burn = remaining / months_remaining
                month_spend += monthly_burn

            forecasts.append({
                "month": month_date.strftime("%Y-%m"),
                "projected_spend": month_spend
            })

        return forecasts

    def save_snapshot(self):
        """儲存當前狀態以供趨勢分析。"""
        summary = self.calculate_portfolio_summary()
        if summary:
            self.snapshots.append({
                "date": datetime.now(),
                "avg_cpi": summary.avg_cpi,
                "avg_spi": summary.avg_spi,
                "on_budget_pct": summary.on_budget_pct,
                "on_schedule_pct": summary.on_schedule_pct,
                "total_forecast": summary.total_forecast_cost
            })

    def generate_report(self) -> str:
        """產生組合儀表板報告。"""
        summary = self.calculate_portfolio_summary()

        if not summary:
            return "組合中沒有專案"

        lines = [
            "# 專案組合儀表板",
            "",
            f"**組合名稱:** {self.portfolio_name}",
            f"**報告日期:** {summary.report_date.strftime('%Y-%m-%d')}",
            "",
            "## 摘要",
            "",
            f"| 指標 | 數值 |",
            f"|--------|-------|",
            f"| 總專案數 | {summary.total_projects} ({summary.active_projects} 個進行中) |",
            f"| 總合約價值 | ${summary.total_contract_value:,.0f} |",
            f"| 總預算 | ${summary.total_budget:,.0f} |",
            f"| 累計實際成本 | ${summary.total_actual_cost:,.0f} |",
            f"| 完工預測 | ${summary.total_forecast_cost:,.0f} |",
            f"| 平均 CPI | {summary.avg_cpi:.2f} |",
            f"| 平均 SPI | {summary.avg_spi:.2f} |",
            f"| 預算內比例 | {summary.on_budget_pct:.1f}% |",
            f"| 準時完成比例 | {summary.on_schedule_pct:.1f}% |",
            f"| 組合 TRIR | {summary.portfolio_trir:.2f} |",
            f"| 總事故數 | {summary.total_incidents} |",
            "",
            "## 專案健康狀態",
            "",
            f"| 狀態 | 數量 |",
            f"|--------|-------|",
            f"| 🟢 正常 | {summary.green_count} |",
            f"| 🟡 有風險 | {summary.yellow_count} |",
            f"| 🔴 危急 | {summary.red_count} |",
            "",
            "## 趨勢",
            "",
            f"- **成本趨勢:** {summary.cost_trend}",
            f"- **進度趨勢:** {summary.schedule_trend}",
            "",
            "---",
            "",
            "*由 Portfolio Dashboard 自動產生*"
        ]

        return "\n".join(lines)

使用範例

# 創建組合儀表板
portfolio = PortfolioDashboard("建築專案組合 2024")

# 匯入專案數據
projects_data = [
    {
        'id': 'PRJ-001',
        'name': '河濱大橋',
        'status': 'active',
        'contract_value': 50000000,
        'percent_complete': 45,
        'planned_start': datetime(2024, 1, 1),
        'planned_end': datetime(2025, 6, 30),
        'forecast_end': datetime(2025, 8, 15),
        'budget': 45000000,
        'actual_cost': 20000000,
        'forecast_cost': 48000000,
        'cpi': 0.92,
        'spi': 0.88,
        'incidents': 2,
        'total_hours': 150000,
        'risk_score': 6.5,
        'critical_risks': 2
    },
    {
        'id': 'PRJ-002',
        'name': '市中心隧道',
        'status': 'active',
        'contract_value': 80000000,
        'percent_complete': 30,
        'planned_start': datetime(2024, 3, 1),
        'planned_end': datetime(2026, 12, 31),
        'forecast_end': datetime(2026, 12, 31),
        'budget': 75000000,
        'actual_cost': 22000000,
        'forecast_cost': 75000000,
        'cpi': 1.02,
        'spi': 1.0,
        'incidents': 0,
        'total_hours': 200000,
        'risk_score': 3.2,
        'critical_risks': 0
    }
]

count = portfolio.import_projects(projects_data)
print(f"已匯入 {count} 個專案")

# 計算組合摘要
summary = portfolio.calculate_portfolio_summary()
print(f"平均 CPI: {summary.avg_cpi:.2f}")
print(f"預算內比例: {summary.on_budget_pct:.1f}%")

# 比較專案
comparison = portfolio.compare_projects("cpi")
print(f"CPI 表現最佳: {comparison.best[0]} ({comparison.best[1]:.2f})")
print(f"CPI 表現最差: {comparison.worst[0]} ({comparison.worst[1]:.2f})")

# 識別風險
at_risk = portfolio.get_projects_at_risk()
print(f"需要注意的專案: {len(at_risk)}")

# 預測現金流
forecasts = portfolio.forecast_cash_needs(months=6)
for f in forecasts:
    print(f"{f['month']}: ${f['projected_spend']:,.0f}")

# 保存快照
portfolio.save_snapshot()

# 產生報告
report = portfolio.generate_report()
print(report)

輸出範例

當產生報告時,您會看到類似以下的輸出:

# 專案組合儀表板

**組合名稱:** 建築專案組合 2024
**報告日期:** 2024-08-20

## 摘要

| 指標 | 數值 |
|--------|-------|
| 總專案數 | 2 (2 個進行中) |
| 總合約價值 | $130,000,000 |
| 總預算 | $120,000,000 |
| 累計實際成本 | $42,000,000 |
| 完工預測 | $123,000,000 |
| 平均 CPI | 0.97 |
| 平均 SPI | 0.94 |
| 預算內比例 | 50.0% |
| 準時完成比例 | 50.0% |
| 組合 TRIR | 1.71 |
| 總事故數 | 2 |

## 專案健康狀態

| 狀態 | 數量 |
|--------|-------|
| 🟢 正常 | 1 |
| 🟡 有風險 | 1 |
| 🔴 危急 | 0 |

## 趨勢

- **成本趨勢:** 穩定
- **進度趨勢:** 穩定

---

*由 Portfolio Dashboard 自動產生*

主要功能

  • 組合摘要: 計算總合約價值、預算、成本及預測
  • 績效指標: 預算內比例與準時完成比例
  • 專案健康狀態: 自動將專案分類為正常、有風險、危急或未開始
  • 比較: 跨所有進行中專案進行排名與基準測試
  • 風險識別: 標記需要管理階層注意的專案
  • 現金流預測: 預測未來幾個月的資金需求
  • 趨勢追蹤: 儲存歷史快照以監控績效趨勢
  • 報告產生: 自動產生儀表板報告

組態

可以自訂以下閾值:

# 預設閾值可在 PortfolioDashboard.THRESHOLDS 中找到
{
    "cpi_warning": 0.95,          # CPI 低於此值發出警告
    "cpi_critical": 0.85,         # CPI 低於此值視為危急
    "spi_warning": 0.95,          # SPI 低於此值發出警告
    "spi_critical": 0.85,         # SPI 低於此值視為危急
    "trir_warning": 2.0,          # TRIR 高於此值發出警告
    "risk_score_warning": 7.0     # 風險評分高於此值發出警告
}

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

Portfolio allocation and rebalancing optimizer. Manages asset allocation across stocks/cash/bonds, performs periodic rebalancing, and ensures diversification according to market regime and risk tolerance.

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

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

相關技能