Communitygithub.com

專案組合儀表板

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

專案組合儀表板 是什麼?

Portfolio Dashboard 是一款專為多專案組合分析設計的工具,主要針對營造工程領域。它能匯總多個專案的資料,提供組合層級的可見性,協助使用者追蹤關鍵績效指標(KPI),如總合約價值、按時完成率、預算內完成率、安全記錄率、風險評分及資源利用率。 該技能支援透過 Python 程式碼直接整合,提供 PortfolioDashboard 類別,可匯入專案資料(包含成本、時程、安全、品質和風險等維度),並自動根據 CPI 和 SPI 等指標計算專案健康狀態(綠/黃/紅/灰)。核心功能包括:計算組合摘要統計、跨專案指標比較、識別風險專案、預測未來現金需求,以及生成結構化的組合報告。 此技能特別適用於需要整合多個營造專案資料的專案管理辦公室(PMO)或高階主管,能透過統一的儀表板資訊,支援策略性資源配置與決策。它是一個可程式化的資料分析框架,而非預先建置的視覺化儀表板。

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

在你喜歡的 AI 中提問

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

說明文件

專案組合儀表板 是做什麼的?

概述

匯總並分析多個營造專案的資料,以獲得組合層級的可視性。追蹤關鍵績效指標,識別趨勢,比較專案績效,並支援策略性資源配置決策。

專案組合分析框架

┌─────────────────────────────────────────────────────────────────┐
│                  專案組合儀表板                                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  專案 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 = "stable"
        schedule_trend = "stable"

        if self.snapshots:
            prev = self.snapshots[-1]
            if avg_cpi > prev.get('avg_cpi', 1.0):
                cost_trend = "improving"
            elif avg_cpi < prev.get('avg_cpi', 1.0):
                cost_trend = "declining"

            if avg_spi > prev.get('avg_spi', 1.0):
                schedule_trend = "improving"
            elif avg_spi < prev.get('avg_spi', 1.0):
                schedule_trend = "declining"

        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"| 指標 | 數值 | 趨勢 |",
            f"|--------|-------|-------|",
            f"| 平均成本績效指數 (CPI) | {summary.avg_cpi:.2f} | {summary.cost_trend} |",
            f"| 平均時程績效指數 (SPI) | {summary.avg_spi:.2f} | {summary.schedule_trend} |",
            f"| 預算內完成率 | {summary.on_budget_pct:.1f}% | |",
            f"| 按時完成率 | {summary.on_schedule_pct:.1f}% | |",
            "",
            "## 安全指標",
            "",
            f"| 指標 | 數值 |",
            f"|--------|-------|",
            f"| 組合總可記錄事故發生率 (TRIR) | {summary.portfolio_trir:.2f} |",
            f"| 總事故數 | {summary.total_incidents} |",
            "",
            "## 健康狀態分佈",
            "",
            f"| 狀態 | 數量 | 百分比 |",
            f"|--------|-------|---------|",
            f"| 🟢 正常 (GREEN) | {summary.green_count} | {(summary.green_count/summary.active_projects*100):.1f}% |" if summary.active_projects > 0 else f"| 🟢 正常 (GREEN) | {summary.green_count} | 0% |",
            f"| 🟡 有風險 (YELLOW) | {summary.yellow_count} | {(summary.yellow_count/summary.active_projects*100):.1f}% |" if summary.active_projects > 0 else f"| 🟡 有風險 (YELLOW) | {summary.yellow_count} | 0% |",
            f"| 🔴 危急 (RED) | {summary.red_count} | {(summary.red_count/summary.active_projects*100):.1f}% |" if summary.active_projects > 0 else f"| 🔴 危急 (RED) | {summary.red_count} | 0% |"
        ]

        # 風險專案
        risks = self.get_projects_at_risk()
        if risks:
            lines.extend([
                "",
                "## 需要關注的專案",
                "",
                "| 專案名稱 | 健康狀態 | CPI | SPI |",
                "|--------------|--------|-------|-------|",
            ])
            for p in risks:
                health_emoji = {
                    HealthStatus.RED: "🔴",
                    HealthStatus.YELLOW: "🟡"
                }.get(p.health, "⚪")
                lines.append(f"| {p.project_name} | {health_emoji} {p.health.value} | {p.cpi:.2f} | {p.spi:.2f} |")

        return "\n".join(lines)


# 使用範例
if __name__ == "__main__":
    # 建立組合儀表板
    dashboard = PortfolioDashboard("基礎建設組合")

    # 範例專案資料
    projects_data = [
        {
            "id": "PRJ-001",
            "name": "高速公路擴建",
            "status": "active",
            "contract_value": 50000000,
            "percent_complete": 65,
            "planned_start": datetime(2024, 1, 1),
            "planned_end": datetime(2025, 6, 30),
            "actual_start": datetime(2024, 1, 15),
            "forecast_end": datetime(2025, 8, 15),
            "budget": 45000000,
            "actual_cost": 28000000,
            "forecast_cost": 47000000,
            "cpi": 0.93,
            "spi": 0.91,
            "incidents": 2,
            "total_hours": 150000,
            "risk_score": 6.5,
            "critical_risks": 2
        },
        {
            "id": "PRJ-002",
            "name": "橋樑重建",
            "status": "active",
            "contract_value": 25000000,
            "percent_complete": 40,
            "planned_start": datetime(2024, 3, 1),
            "planned_end": datetime(2025, 12, 31),
            "actual_start": datetime(2024, 3, 10),
            "forecast_end": datetime(2025, 12, 15),
            "budget": 22000000,
            "actual_cost": 8500000,
            "forecast_cost": 21500000,
            "cpi": 1.02,
            "spi": 1.05,
            "incidents": 0,
            "total_hours": 80000,
            "risk_score": 3.2,
            "critical_risks": 0
        }
    ]

    # 匯入專案
    imported = dashboard.import_projects(projects_data)
    print(f"已匯入 {imported} 個專案")

    # 產生並顯示報告
    report = dashboard.generate_report()
    print(report)

使用說明

PortfolioDashboard 類別提供可程式化的方法來:

  1. 匯入專案資料:使用 import_projects() 從字典列表載入多個專案
  2. 分析組合:使用 calculate_portfolio_summary() 計算匯總指標
  3. 比較專案:使用 compare_projects() 依特定指標比較專案
  4. 識別風險:使用 get_projects_at_risk() 和 get_top_risks() 找出風險項目
  5. 預測需求:使用 forecast_cash_needs() 預測未來現金需求
  6. 產生報告:使用 generate_report() 建立結構化的 Markdown 報告
  7. 追蹤趨勢:使用 save_snapshot() 儲存歷史快照以進行趨勢分析

此技能專為需要跨多個營造專案彙總和分析資料的專案經理、專案管理辦公室 (PMO) 團隊和高階主管所設計。

Individual skills in this repo

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

majiayu000/claude-skill-registry-data

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry-data

Edit existing BMAD agents while maintaining compliance

majiayu000/claude-skill-registry-data

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry-data

Edit existing BMAD modules while maintaining coherence

majiayu000/claude-skill-registry-data

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-data

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-data

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-data

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-data

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-data

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

majiayu000/claude-skill-registry-data

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-data

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

majiayu000/claude-skill-registry-data

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-data

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-data

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-data

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

majiayu000/claude-skill-registry-data

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

majiayu000/claude-skill-registry-data

Conduct market research on competition and customers. Use when the user says "create a market research report about [business idea]".

majiayu000/claude-skill-registry-data

Conduct technical research on technologies and architecture. Use when the user says "create a technical research report on [topic]".

majiayu000/claude-skill-registry-data

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".

相關技能