[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FJJE6X0RSRT2KTBFMMKCG5":3,"skill-same:01M6FJJE6X0RSRT2KTBFMMKCG5":58},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":25,"linkOnly":26,"markdownContent":27,"markdownBody":28,"frontMatter":29,"refName":31,"commitSha":32,"skillDirectory":33,"forksCount":34,"repositoryHtmlUrl":35,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":37,"install":38,"resources":51},"01M6FJJE6X0RSRT2KTBFMMKCG5","budget-variance-analyzer",null,"Analyze budget vs actual cost variances. Identify overruns, forecast final costs, and generate variance reports.","kbarbel640-del\u002Fskills","kbarbel640-del","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F255315490?v=4","01M6CJPPQGCCESXMG3K7BBGQ5J","01M6CJPPX2PB2BCZERFVM2C2B3",1,"MIT","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fbudget-variance-analyzer\u002FSKILL.md",[],[18,19,20,21,22,23,24],"Budget","budget variance analyzer","forecast","generate","analyze","cost","reports","2026-11-10 10:12:30",false,"---\r\nslug: \"budget-variance-analyzer\"\r\ndisplay_name: \"Budget Variance Analyzer\"\r\ndescription: \"Analyze budget vs actual cost variances. Identify overruns, forecast final costs, and generate variance reports.\"\r\n---\r\n\r\n# Budget Variance Analyzer\r\n\r\n## Business Case\r\n\r\n### Problem Statement\r\nCost overruns surprise project teams:\r\n- Late detection of budget issues\r\n- No systematic variance analysis\r\n- Difficult to forecast final costs\r\n- Unclear root causes\r\n\r\n### Solution\r\nSystematic budget variance analysis that tracks costs against budget, identifies trends, and forecasts final project costs.\r\n\r\n### Business Value\r\n- **Early warning** - Detect overruns early\r\n- **Forecasting** - Predict final costs\r\n- **Accountability** - Track variance causes\r\n- **Decision support** - Informed cost decisions\r\n\r\n## Technical Implementation\r\n\r\n```python\r\nimport pandas as pd\r\nfrom datetime import datetime, date\r\nfrom typing import Dict, Any, List, Optional, Tuple\r\nfrom dataclasses import dataclass, field\r\nfrom enum import Enum\r\n\r\n\r\nclass VarianceStatus(Enum):\r\n    \"\"\"Variance status.\"\"\"\r\n    UNDER_BUDGET = \"under_budget\"\r\n    ON_BUDGET = \"on_budget\"\r\n    OVER_BUDGET = \"over_budget\"\r\n    CRITICAL = \"critical\"\r\n\r\n\r\nclass CostCategory(Enum):\r\n    \"\"\"Cost categories.\"\"\"\r\n    LABOR = \"labor\"\r\n    MATERIAL = \"material\"\r\n    EQUIPMENT = \"equipment\"\r\n    SUBCONTRACTOR = \"subcontractor\"\r\n    OVERHEAD = \"overhead\"\r\n    CONTINGENCY = \"contingency\"\r\n    OTHER = \"other\"\r\n\r\n\r\nclass VarianceCause(Enum):\r\n    \"\"\"Common variance causes.\"\"\"\r\n    SCOPE_CHANGE = \"scope_change\"\r\n    QUANTITY_CHANGE = \"quantity_change\"\r\n    PRICE_ESCALATION = \"price_escalation\"\r\n    PRODUCTIVITY = \"productivity\"\r\n    REWORK = \"rework\"\r\n    DELAY = \"delay\"\r\n    UNFORESEEN = \"unforeseen\"\r\n    ESTIMATE_ERROR = \"estimate_error\"\r\n    OTHER = \"other\"\r\n\r\n\r\n@dataclass\r\nclass BudgetItem:\r\n    \"\"\"Single budget line item.\"\"\"\r\n    item_code: str\r\n    description: str\r\n    category: CostCategory\r\n    original_budget: float\r\n    current_budget: float  # After approved changes\r\n    committed_cost: float  # Contracts, POs\r\n    actual_cost: float     # Paid\u002Finvoiced\r\n    forecast_cost: float   # Estimate at completion\r\n    percent_complete: float\r\n    notes: str = \"\"\r\n\r\n    @property\r\n    def variance_amount(self) -> float:\r\n        \"\"\"Budget variance (negative = over budget).\"\"\"\r\n        return self.current_budget - self.forecast_cost\r\n\r\n    @property\r\n    def variance_percent(self) -> float:\r\n        \"\"\"Variance as percentage.\"\"\"\r\n        if self.current_budget == 0:\r\n            return 0\r\n        return (self.variance_amount \u002F self.current_budget) * 100\r\n\r\n    @property\r\n    def status(self) -> VarianceStatus:\r\n        \"\"\"Determine variance status.\"\"\"\r\n        pct = self.variance_percent\r\n        if pct > 5:\r\n            return VarianceStatus.UNDER_BUDGET\r\n        elif pct >= -5:\r\n            return VarianceStatus.ON_BUDGET\r\n        elif pct >= -15:\r\n            return VarianceStatus.OVER_BUDGET\r\n        else:\r\n            return VarianceStatus.CRITICAL\r\n\r\n\r\n@dataclass\r\nclass VarianceRecord:\r\n    \"\"\"Record of budget variance.\"\"\"\r\n    record_id: str\r\n    item_code: str\r\n    variance_amount: float\r\n    cause: VarianceCause\r\n    explanation: str\r\n    recorded_date: date\r\n    recorded_by: str\r\n    approved: bool = False\r\n    approval_date: Optional[date] = None\r\n\r\n\r\n@dataclass\r\nclass ForecastScenario:\r\n    \"\"\"Cost forecast scenario.\"\"\"\r\n    name: str\r\n    description: str\r\n    adjustments: Dict[str, float]  # item_code: adjustment amount\r\n    total_forecast: float\r\n    variance_from_budget: float\r\n\r\n\r\nclass BudgetVarianceAnalyzer:\r\n    \"\"\"Analyze budget vs actual cost variances.\"\"\"\r\n\r\n    VARIANCE_THRESHOLD_WARNING = -0.05  # -5%\r\n    VARIANCE_THRESHOLD_CRITICAL = -0.15  # -15%\r\n\r\n    def __init__(self, project_name: str, original_budget: float, currency: str = \"USD\"):\r\n        self.project_name = project_name\r\n        self.original_budget = original_budget\r\n        self.currency = currency\r\n        self.items: Dict[str, BudgetItem] = {}\r\n        self.variance_records: List[VarianceRecord] = []\r\n        self.history: List[Dict[str, Any]] = []\r\n\r\n    def add_budget_item(self,\r\n                       item_code: str,\r\n                       description: str,\r\n                       category: CostCategory,\r\n                       budget: float,\r\n                       committed: float = 0,\r\n                       actual: float = 0,\r\n                       percent_complete: float = 0) -> BudgetItem:\r\n        \"\"\"Add budget line item.\"\"\"\r\n        forecast = max(committed, actual \u002F percent_complete * 100) if percent_complete > 0 else budget\r\n\r\n        item = BudgetItem(\r\n            item_code=item_code,\r\n            description=description,\r\n            category=category,\r\n            original_budget=budget,\r\n            current_budget=budget,\r\n            committed_cost=committed,\r\n            actual_cost=actual,\r\n            forecast_cost=forecast,\r\n            percent_complete=percent_complete\r\n        )\r\n\r\n        self.items[item_code] = item\r\n        return item\r\n\r\n    def update_costs(self, item_code: str,\r\n                    committed: float = None,\r\n                    actual: float = None,\r\n                    percent_complete: float = None,\r\n                    forecast: float = None):\r\n        \"\"\"Update item costs.\"\"\"\r\n        if item_code not in self.items:\r\n            raise ValueError(f\"Item {item_code} not found\")\r\n\r\n        item = self.items[item_code]\r\n\r\n        if committed is not None:\r\n            item.committed_cost = committed\r\n        if actual is not None:\r\n            item.actual_cost = actual\r\n        if percent_complete is not None:\r\n            item.percent_complete = percent_complete\r\n        if forecast is not None:\r\n            item.forecast_cost = forecast\r\n        else:\r\n            # Auto-calculate forecast\r\n            if item.percent_complete > 0:\r\n                item.forecast_cost = item.actual_cost \u002F item.percent_complete * 100\r\n            else:\r\n                item.forecast_cost = max(item.committed_cost, item.current_budget)\r\n\r\n        self._record_history()\r\n\r\n    def adjust_budget(self, item_code: str, amount: float, reason: str):\r\n        \"\"\"Adjust current budget (approved change).\"\"\"\r\n        if item_code not in self.items:\r\n            raise ValueError(f\"Item {item_code} not found\")\r\n\r\n        self.items[item_code].current_budget += amount\r\n        self.items[item_code].notes += f\"\\nBudget adjusted by {amount}: {reason}\"\r\n\r\n    def record_variance(self,\r\n                       item_code: str,\r\n                       cause: VarianceCause,\r\n                       explanation: str,\r\n                       recorded_by: str) -> VarianceRecord:\r\n        \"\"\"Record variance explanation.\"\"\"\r\n        item = self.items.get(item_code)\r\n        if not item:\r\n            raise ValueError(f\"Item {item_code} not found\")\r\n\r\n        record_id = f\"VAR-{len(self.variance_records) + 1:04d}\"\r\n\r\n        record = VarianceRecord(\r\n            record_id=record_id,\r\n            item_code=item_code,\r\n            variance_amount=item.variance_amount,\r\n            cause=cause,\r\n            explanation=explanation,\r\n            recorded_date=date.today(),\r\n            recorded_by=recorded_by\r\n        )\r\n\r\n        self.variance_records.append(record)\r\n        return record\r\n\r\n    def _record_history(self):\r\n        \"\"\"Record current state to history.\"\"\"\r\n        snapshot = {\r\n            'date': date.today().isoformat(),\r\n            'total_budget': sum(i.current_budget for i in self.items.values()),\r\n            'total_committed': sum(i.committed_cost for i in self.items.values()),\r\n            'total_actual': sum(i.actual_cost for i in self.items.values()),\r\n            'total_forecast': sum(i.forecast_cost for i in self.items.values())\r\n        }\r\n        self.history.append(snapshot)\r\n\r\n    def calculate_summary(self) -> Dict[str, Any]:\r\n        \"\"\"Calculate overall budget summary.\"\"\"\r\n        total_budget = sum(i.current_budget for i in self.items.values())\r\n        total_committed = sum(i.committed_cost for i in self.items.values())\r\n        total_actual = sum(i.actual_cost for i in self.items.values())\r\n        total_forecast = sum(i.forecast_cost for i in self.items.values())\r\n\r\n        variance = total_budget - total_forecast\r\n        variance_pct = (variance \u002F total_budget * 100) if total_budget > 0 else 0\r\n\r\n        # By category\r\n        by_category = {}\r\n        for item in self.items.values():\r\n            cat = item.category.value\r\n            if cat not in by_category:\r\n                by_category[cat] = {\r\n                    'budget': 0, 'actual': 0, 'forecast': 0, 'variance': 0\r\n                }\r\n            by_category[cat]['budget'] += item.current_budget\r\n            by_category[cat]['actual'] += item.actual_cost\r\n            by_category[cat]['forecast'] += item.forecast_cost\r\n            by_category[cat]['variance'] += item.variance_amount\r\n\r\n        # Items needing attention\r\n        critical = [i for i in self.items.values() if i.status == VarianceStatus.CRITICAL]\r\n        over_budget = [i for i in self.items.values() if i.status == VarianceStatus.OVER_BUDGET]\r\n\r\n        return {\r\n            'project': self.project_name,\r\n            'currency': self.currency,\r\n            'original_budget': self.original_budget,\r\n            'current_budget': total_budget,\r\n            'committed': total_committed,\r\n            'actual': total_actual,\r\n            'forecast': total_forecast,\r\n            'variance': variance,\r\n            'variance_percent': round(variance_pct, 1),\r\n            'status': 'ON_TRACK' if variance >= 0 else 'OVER_BUDGET',\r\n            'by_category': by_category,\r\n            'critical_items': len(critical),\r\n            'over_budget_items': len(over_budget),\r\n            'contingency_used': total_budget - self.original_budget\r\n        }\r\n\r\n    def get_critical_items(self) -> List[BudgetItem]:\r\n        \"\"\"Get items with critical variances.\"\"\"\r\n        return [i for i in self.items.values()\r\n                if i.status in [VarianceStatus.CRITICAL, VarianceStatus.OVER_BUDGET]]\r\n\r\n    def forecast_completion(self,\r\n                           optimistic_factor: float = 0.95,\r\n                           pessimistic_factor: float = 1.15) -> Dict[str, ForecastScenario]:\r\n        \"\"\"Generate forecast scenarios.\"\"\"\r\n        current_forecast = sum(i.forecast_cost for i in self.items.values())\r\n        current_budget = sum(i.current_budget for i in self.items.values())\r\n\r\n        scenarios = {\r\n            'optimistic': ForecastScenario(\r\n                name=\"Optimistic\",\r\n                description=\"Best case with no further overruns\",\r\n                adjustments={},\r\n                total_forecast=current_forecast * optimistic_factor,\r\n                variance_from_budget=current_budget - (current_forecast * optimistic_factor)\r\n            ),\r\n            'most_likely': ForecastScenario(\r\n                name=\"Most Likely\",\r\n                description=\"Current trend continues\",\r\n                adjustments={},\r\n                total_forecast=current_forecast,\r\n                variance_from_budget=current_budget - current_forecast\r\n            ),\r\n            'pessimistic': ForecastScenario(\r\n                name=\"Pessimistic\",\r\n                description=\"Additional overruns expected\",\r\n                adjustments={},\r\n                total_forecast=current_forecast * pessimistic_factor,\r\n                variance_from_budget=current_budget - (current_forecast * pessimistic_factor)\r\n            )\r\n        }\r\n\r\n        return scenarios\r\n\r\n    def analyze_trends(self) -> Dict[str, Any]:\r\n        \"\"\"Analyze cost trends from history.\"\"\"\r\n        if len(self.history) \u003C 2:\r\n            return {'trend': 'insufficient_data'}\r\n\r\n        forecasts = [h['total_forecast'] for h in self.history]\r\n        actuals = [h['total_actual'] for h in self.history]\r\n\r\n        # Calculate trend direction\r\n        forecast_trend = forecasts[-1] - forecasts[0]\r\n        actual_trend = actuals[-1] - actuals[0]\r\n\r\n        return {\r\n            'forecast_trend': 'increasing' if forecast_trend > 0 else 'decreasing',\r\n            'forecast_change': forecast_trend,\r\n            'actual_trend': 'increasing' if actual_trend > 0 else 'stable',\r\n            'actual_change': actual_trend,\r\n            'data_points': len(self.history)\r\n        }\r\n\r\n    def export_variance_report(self, output_path: str):\r\n        \"\"\"Export detailed variance report to Excel.\"\"\"\r\n        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:\r\n            # Summary\r\n            summary = self.calculate_summary()\r\n            summary_df = pd.DataFrame([\r\n                {'Metric': k, 'Value': v}\r\n                for k, v in summary.items()\r\n                if not isinstance(v, dict)\r\n            ])\r\n            summary_df.to_excel(writer, sheet_name='Summary', index=False)\r\n\r\n            # Line items\r\n            items_data = []\r\n            for item in self.items.values():\r\n                items_data.append({\r\n                    'Code': item.item_code,\r\n                    'Description': item.description,\r\n                    'Category': item.category.value,\r\n                    'Budget': item.current_budget,\r\n                    'Committed': item.committed_cost,\r\n                    'Actual': item.actual_cost,\r\n                    'Forecast': item.forecast_cost,\r\n                    'Variance $': item.variance_amount,\r\n                    'Variance %': round(item.variance_percent, 1),\r\n                    'Status': item.status.value,\r\n                    '% Complete': item.percent_complete\r\n                })\r\n\r\n            pd.DataFrame(items_data).to_excel(writer, sheet_name='Line Items', index=False)\r\n\r\n            # Variance records\r\n            if self.variance_records:\r\n                records_df = pd.DataFrame([{\r\n                    'ID': r.record_id,\r\n                    'Item': r.item_code,\r\n                    'Amount': r.variance_amount,\r\n                    'Cause': r.cause.value,\r\n                    'Explanation': r.explanation,\r\n                    'Date': r.recorded_date,\r\n                    'By': r.recorded_by\r\n                } for r in self.variance_records])\r\n                records_df.to_excel(writer, sheet_name='Variance Records', index=False)\r\n\r\n        return output_path\r\n```\r\n\r\n## Quick Start\r\n\r\n```python\r\n# Initialize analyzer\r\nanalyzer = BudgetVarianceAnalyzer(\r\n    project_name=\"Office Tower\",\r\n    original_budget=50000000,\r\n    currency=\"USD\"\r\n)\r\n\r\n# Add budget items\r\nanalyzer.add_budget_item(\"01-SITE\", \"Site Work\", CostCategory.SUBCONTRACTOR, 2000000)\r\nanalyzer.add_budget_item(\"03-CONC\", \"Concrete\", CostCategory.SUBCONTRACTOR, 8000000)\r\nanalyzer.add_budget_item(\"05-STEEL\", \"Structural Steel\", CostCategory.SUBCONTRACTOR, 6000000)\r\n\r\n# Update with actuals\r\nanalyzer.update_costs(\"03-CONC\", committed=8500000, actual=4000000, percent_complete=45)\r\n\r\n# Get summary\r\nsummary = analyzer.calculate_summary()\r\nprint(f\"Variance: ${summary['variance']:,.0f} ({summary['variance_percent']}%)\")\r\n```\r\n\r\n## Common Use Cases\r\n\r\n### 1. Monthly Cost Review\r\n```python\r\nsummary = analyzer.calculate_summary()\r\ncritical = analyzer.get_critical_items()\r\nprint(f\"Items needing attention: {len(critical)}\")\r\n```\r\n\r\n### 2. Record Variance Cause\r\n```python\r\nanalyzer.record_variance(\r\n    item_code=\"03-CONC\",\r\n    cause=VarianceCause.PRICE_ESCALATION,\r\n    explanation=\"Steel rebar prices increased 15%\",\r\n    recorded_by=\"Cost Manager\"\r\n)\r\n```\r\n\r\n### 3. Forecast Scenarios\r\n```python\r\nscenarios = analyzer.forecast_completion()\r\nfor name, scenario in scenarios.items():\r\n    print(f\"{scenario.name}: ${scenario.total_forecast:,.0f}\")\r\n```\r\n\r\n## Resources\r\n- **DDC Book**: Chapter 3.1 - Cost Management\r\n- **Reference**: PMI Cost Management\r\n","# Budget Variance Analyzer\r\n\r\n## Business Case\r\n\r\n### Problem Statement\r\nCost overruns surprise project teams:\r\n- Late detection of budget issues\r\n- No systematic variance analysis\r\n- Difficult to forecast final costs\r\n- Unclear root causes\r\n\r\n### Solution\r\nSystematic budget variance analysis that tracks costs against budget, identifies trends, and forecasts final project costs.\r\n\r\n### Business Value\r\n- **Early warning** - Detect overruns early\r\n- **Forecasting** - Predict final costs\r\n- **Accountability** - Track variance causes\r\n- **Decision support** - Informed cost decisions\r\n\r\n## Technical Implementation\r\n\r\n```python\r\nimport pandas as pd\r\nfrom datetime import datetime, date\r\nfrom typing import Dict, Any, List, Optional, Tuple\r\nfrom dataclasses import dataclass, field\r\nfrom enum import Enum\r\n\r\n\r\nclass VarianceStatus(Enum):\r\n    \"\"\"Variance status.\"\"\"\r\n    UNDER_BUDGET = \"under_budget\"\r\n    ON_BUDGET = \"on_budget\"\r\n    OVER_BUDGET = \"over_budget\"\r\n    CRITICAL = \"critical\"\r\n\r\n\r\nclass CostCategory(Enum):\r\n    \"\"\"Cost categories.\"\"\"\r\n    LABOR = \"labor\"\r\n    MATERIAL = \"material\"\r\n    EQUIPMENT = \"equipment\"\r\n    SUBCONTRACTOR = \"subcontractor\"\r\n    OVERHEAD = \"overhead\"\r\n    CONTINGENCY = \"contingency\"\r\n    OTHER = \"other\"\r\n\r\n\r\nclass VarianceCause(Enum):\r\n    \"\"\"Common variance causes.\"\"\"\r\n    SCOPE_CHANGE = \"scope_change\"\r\n    QUANTITY_CHANGE = \"quantity_change\"\r\n    PRICE_ESCALATION = \"price_escalation\"\r\n    PRODUCTIVITY = \"productivity\"\r\n    REWORK = \"rework\"\r\n    DELAY = \"delay\"\r\n    UNFORESEEN = \"unforeseen\"\r\n    ESTIMATE_ERROR = \"estimate_error\"\r\n    OTHER = \"other\"\r\n\r\n\r\n@dataclass\r\nclass BudgetItem:\r\n    \"\"\"Single budget line item.\"\"\"\r\n    item_code: str\r\n    description: str\r\n    category: CostCategory\r\n    original_budget: float\r\n    current_budget: float  # After approved changes\r\n    committed_cost: float  # Contracts, POs\r\n    actual_cost: float     # Paid\u002Finvoiced\r\n    forecast_cost: float   # Estimate at completion\r\n    percent_complete: float\r\n    notes: str = \"\"\r\n\r\n    @property\r\n    def variance_amount(self) -> float:\r\n        \"\"\"Budget variance (negative = over budget).\"\"\"\r\n        return self.current_budget - self.forecast_cost\r\n\r\n    @property\r\n    def variance_percent(self) -> float:\r\n        \"\"\"Variance as percentage.\"\"\"\r\n        if self.current_budget == 0:\r\n            return 0\r\n        return (self.variance_amount \u002F self.current_budget) * 100\r\n\r\n    @property\r\n    def status(self) -> VarianceStatus:\r\n        \"\"\"Determine variance status.\"\"\"\r\n        pct = self.variance_percent\r\n        if pct > 5:\r\n            return VarianceStatus.UNDER_BUDGET\r\n        elif pct >= -5:\r\n            return VarianceStatus.ON_BUDGET\r\n        elif pct >= -15:\r\n            return VarianceStatus.OVER_BUDGET\r\n        else:\r\n            return VarianceStatus.CRITICAL\r\n\r\n\r\n@dataclass\r\nclass VarianceRecord:\r\n    \"\"\"Record of budget variance.\"\"\"\r\n    record_id: str\r\n    item_code: str\r\n    variance_amount: float\r\n    cause: VarianceCause\r\n    explanation: str\r\n    recorded_date: date\r\n    recorded_by: str\r\n    approved: bool = False\r\n    approval_date: Optional[date] = None\r\n\r\n\r\n@dataclass\r\nclass ForecastScenario:\r\n    \"\"\"Cost forecast scenario.\"\"\"\r\n    name: str\r\n    description: str\r\n    adjustments: Dict[str, float]  # item_code: adjustment amount\r\n    total_forecast: float\r\n    variance_from_budget: float\r\n\r\n\r\nclass BudgetVarianceAnalyzer:\r\n    \"\"\"Analyze budget vs actual cost variances.\"\"\"\r\n\r\n    VARIANCE_THRESHOLD_WARNING = -0.05  # -5%\r\n    VARIANCE_THRESHOLD_CRITICAL = -0.15  # -15%\r\n\r\n    def __init__(self, project_name: str, original_budget: float, currency: str = \"USD\"):\r\n        self.project_name = project_name\r\n        self.original_budget = original_budget\r\n        self.currency = currency\r\n        self.items: Dict[str, BudgetItem] = {}\r\n        self.variance_records: List[VarianceRecord] = []\r\n        self.history: List[Dict[str, Any]] = []\r\n\r\n    def add_budget_item(self,\r\n                       item_code: str,\r\n                       description: str,\r\n                       category: CostCategory,\r\n                       budget: float,\r\n                       committed: float = 0,\r\n                       actual: float = 0,\r\n                       percent_complete: float = 0) -> BudgetItem:\r\n        \"\"\"Add budget line item.\"\"\"\r\n        forecast = max(committed, actual \u002F percent_complete * 100) if percent_complete > 0 else budget\r\n\r\n        item = BudgetItem(\r\n            item_code=item_code,\r\n            description=description,\r\n            category=category,\r\n            original_budget=budget,\r\n            current_budget=budget,\r\n            committed_cost=committed,\r\n            actual_cost=actual,\r\n            forecast_cost=forecast,\r\n            percent_complete=percent_complete\r\n        )\r\n\r\n        self.items[item_code] = item\r\n        return item\r\n\r\n    def update_costs(self, item_code: str,\r\n                    committed: float = None,\r\n                    actual: float = None,\r\n                    percent_complete: float = None,\r\n                    forecast: float = None):\r\n        \"\"\"Update item costs.\"\"\"\r\n        if item_code not in self.items:\r\n            raise ValueError(f\"Item {item_code} not found\")\r\n\r\n        item = self.items[item_code]\r\n\r\n        if committed is not None:\r\n            item.committed_cost = committed\r\n        if actual is not None:\r\n            item.actual_cost = actual\r\n        if percent_complete is not None:\r\n            item.percent_complete = percent_complete\r\n        if forecast is not None:\r\n            item.forecast_cost = forecast\r\n        else:\r\n            # Auto-calculate forecast\r\n            if item.percent_complete > 0:\r\n                item.forecast_cost = item.actual_cost \u002F item.percent_complete * 100\r\n            else:\r\n                item.forecast_cost = max(item.committed_cost, item.current_budget)\r\n\r\n        self._record_history()\r\n\r\n    def adjust_budget(self, item_code: str, amount: float, reason: str):\r\n        \"\"\"Adjust current budget (approved change).\"\"\"\r\n        if item_code not in self.items:\r\n            raise ValueError(f\"Item {item_code} not found\")\r\n\r\n        self.items[item_code].current_budget += amount\r\n        self.items[item_code].notes += f\"\\nBudget adjusted by {amount}: {reason}\"\r\n\r\n    def record_variance(self,\r\n                       item_code: str,\r\n                       cause: VarianceCause,\r\n                       explanation: str,\r\n                       recorded_by: str) -> VarianceRecord:\r\n        \"\"\"Record variance explanation.\"\"\"\r\n        item = self.items.get(item_code)\r\n        if not item:\r\n            raise ValueError(f\"Item {item_code} not found\")\r\n\r\n        record_id = f\"VAR-{len(self.variance_records) + 1:04d}\"\r\n\r\n        record = VarianceRecord(\r\n            record_id=record_id,\r\n            item_code=item_code,\r\n            variance_amount=item.variance_amount,\r\n            cause=cause,\r\n            explanation=explanation,\r\n            recorded_date=date.today(),\r\n            recorded_by=recorded_by\r\n        )\r\n\r\n        self.variance_records.append(record)\r\n        return record\r\n\r\n    def _record_history(self):\r\n        \"\"\"Record current state to history.\"\"\"\r\n        snapshot = {\r\n            'date': date.today().isoformat(),\r\n            'total_budget': sum(i.current_budget for i in self.items.values()),\r\n            'total_committed': sum(i.committed_cost for i in self.items.values()),\r\n            'total_actual': sum(i.actual_cost for i in self.items.values()),\r\n            'total_forecast': sum(i.forecast_cost for i in self.items.values())\r\n        }\r\n        self.history.append(snapshot)\r\n\r\n    def calculate_summary(self) -> Dict[str, Any]:\r\n        \"\"\"Calculate overall budget summary.\"\"\"\r\n        total_budget = sum(i.current_budget for i in self.items.values())\r\n        total_committed = sum(i.committed_cost for i in self.items.values())\r\n        total_actual = sum(i.actual_cost for i in self.items.values())\r\n        total_forecast = sum(i.forecast_cost for i in self.items.values())\r\n\r\n        variance = total_budget - total_forecast\r\n        variance_pct = (variance \u002F total_budget * 100) if total_budget > 0 else 0\r\n\r\n        # By category\r\n        by_category = {}\r\n        for item in self.items.values():\r\n            cat = item.category.value\r\n            if cat not in by_category:\r\n                by_category[cat] = {\r\n                    'budget': 0, 'actual': 0, 'forecast': 0, 'variance': 0\r\n                }\r\n            by_category[cat]['budget'] += item.current_budget\r\n            by_category[cat]['actual'] += item.actual_cost\r\n            by_category[cat]['forecast'] += item.forecast_cost\r\n            by_category[cat]['variance'] += item.variance_amount\r\n\r\n        # Items needing attention\r\n        critical = [i for i in self.items.values() if i.status == VarianceStatus.CRITICAL]\r\n        over_budget = [i for i in self.items.values() if i.status == VarianceStatus.OVER_BUDGET]\r\n\r\n        return {\r\n            'project': self.project_name,\r\n            'currency': self.currency,\r\n            'original_budget': self.original_budget,\r\n            'current_budget': total_budget,\r\n            'committed': total_committed,\r\n            'actual': total_actual,\r\n            'forecast': total_forecast,\r\n            'variance': variance,\r\n            'variance_percent': round(variance_pct, 1),\r\n            'status': 'ON_TRACK' if variance >= 0 else 'OVER_BUDGET',\r\n            'by_category': by_category,\r\n            'critical_items': len(critical),\r\n            'over_budget_items': len(over_budget),\r\n            'contingency_used': total_budget - self.original_budget\r\n        }\r\n\r\n    def get_critical_items(self) -> List[BudgetItem]:\r\n        \"\"\"Get items with critical variances.\"\"\"\r\n        return [i for i in self.items.values()\r\n                if i.status in [VarianceStatus.CRITICAL, VarianceStatus.OVER_BUDGET]]\r\n\r\n    def forecast_completion(self,\r\n                           optimistic_factor: float = 0.95,\r\n                           pessimistic_factor: float = 1.15) -> Dict[str, ForecastScenario]:\r\n        \"\"\"Generate forecast scenarios.\"\"\"\r\n        current_forecast = sum(i.forecast_cost for i in self.items.values())\r\n        current_budget = sum(i.current_budget for i in self.items.values())\r\n\r\n        scenarios = {\r\n            'optimistic': ForecastScenario(\r\n                name=\"Optimistic\",\r\n                description=\"Best case with no further overruns\",\r\n                adjustments={},\r\n                total_forecast=current_forecast * optimistic_factor,\r\n                variance_from_budget=current_budget - (current_forecast * optimistic_factor)\r\n            ),\r\n            'most_likely': ForecastScenario(\r\n                name=\"Most Likely\",\r\n                description=\"Current trend continues\",\r\n                adjustments={},\r\n                total_forecast=current_forecast,\r\n                variance_from_budget=current_budget - current_forecast\r\n            ),\r\n            'pessimistic': ForecastScenario(\r\n                name=\"Pessimistic\",\r\n                description=\"Additional overruns expected\",\r\n                adjustments={},\r\n                total_forecast=current_forecast * pessimistic_factor,\r\n                variance_from_budget=current_budget - (current_forecast * pessimistic_factor)\r\n            )\r\n        }\r\n\r\n        return scenarios\r\n\r\n    def analyze_trends(self) -> Dict[str, Any]:\r\n        \"\"\"Analyze cost trends from history.\"\"\"\r\n        if len(self.history) \u003C 2:\r\n            return {'trend': 'insufficient_data'}\r\n\r\n        forecasts = [h['total_forecast'] for h in self.history]\r\n        actuals = [h['total_actual'] for h in self.history]\r\n\r\n        # Calculate trend direction\r\n        forecast_trend = forecasts[-1] - forecasts[0]\r\n        actual_trend = actuals[-1] - actuals[0]\r\n\r\n        return {\r\n            'forecast_trend': 'increasing' if forecast_trend > 0 else 'decreasing',\r\n            'forecast_change': forecast_trend,\r\n            'actual_trend': 'increasing' if actual_trend > 0 else 'stable',\r\n            'actual_change': actual_trend,\r\n            'data_points': len(self.history)\r\n        }\r\n\r\n    def export_variance_report(self, output_path: str):\r\n        \"\"\"Export detailed variance report to Excel.\"\"\"\r\n        with pd.ExcelWriter(output_path, engine='openpyxl') as writer:\r\n            # Summary\r\n            summary = self.calculate_summary()\r\n            summary_df = pd.DataFrame([\r\n                {'Metric': k, 'Value': v}\r\n                for k, v in summary.items()\r\n                if not isinstance(v, dict)\r\n            ])\r\n            summary_df.to_excel(writer, sheet_name='Summary', index=False)\r\n\r\n            # Line items\r\n            items_data = []\r\n            for item in self.items.values():\r\n                items_data.append({\r\n                    'Code': item.item_code,\r\n                    'Description': item.description,\r\n                    'Category': item.category.value,\r\n                    'Budget': item.current_budget,\r\n                    'Committed': item.committed_cost,\r\n                    'Actual': item.actual_cost,\r\n                    'Forecast': item.forecast_cost,\r\n                    'Variance $': item.variance_amount,\r\n                    'Variance %': round(item.variance_percent, 1),\r\n                    'Status': item.status.value,\r\n                    '% Complete': item.percent_complete\r\n                })\r\n\r\n            pd.DataFrame(items_data).to_excel(writer, sheet_name='Line Items', index=False)\r\n\r\n            # Variance records\r\n            if self.variance_records:\r\n                records_df = pd.DataFrame([{\r\n                    'ID': r.record_id,\r\n                    'Item': r.item_code,\r\n                    'Amount': r.variance_amount,\r\n                    'Cause': r.cause.value,\r\n                    'Explanation': r.explanation,\r\n                    'Date': r.recorded_date,\r\n                    'By': r.recorded_by\r\n                } for r in self.variance_records])\r\n                records_df.to_excel(writer, sheet_name='Variance Records', index=False)\r\n\r\n        return output_path\r\n```\r\n\r\n## Quick Start\r\n\r\n```python\r\n# Initialize analyzer\r\nanalyzer = BudgetVarianceAnalyzer(\r\n    project_name=\"Office Tower\",\r\n    original_budget=50000000,\r\n    currency=\"USD\"\r\n)\r\n\r\n# Add budget items\r\nanalyzer.add_budget_item(\"01-SITE\", \"Site Work\", CostCategory.SUBCONTRACTOR, 2000000)\r\nanalyzer.add_budget_item(\"03-CONC\", \"Concrete\", CostCategory.SUBCONTRACTOR, 8000000)\r\nanalyzer.add_budget_item(\"05-STEEL\", \"Structural Steel\", CostCategory.SUBCONTRACTOR, 6000000)\r\n\r\n# Update with actuals\r\nanalyzer.update_costs(\"03-CONC\", committed=8500000, actual=4000000, percent_complete=45)\r\n\r\n# Get summary\r\nsummary = analyzer.calculate_summary()\r\nprint(f\"Variance: ${summary['variance']:,.0f} ({summary['variance_percent']}%)\")\r\n```\r\n\r\n## Common Use Cases\r\n\r\n### 1. Monthly Cost Review\r\n```python\r\nsummary = analyzer.calculate_summary()\r\ncritical = analyzer.get_critical_items()\r\nprint(f\"Items needing attention: {len(critical)}\")\r\n```\r\n\r\n### 2. Record Variance Cause\r\n```python\r\nanalyzer.record_variance(\r\n    item_code=\"03-CONC\",\r\n    cause=VarianceCause.PRICE_ESCALATION,\r\n    explanation=\"Steel rebar prices increased 15%\",\r\n    recorded_by=\"Cost Manager\"\r\n)\r\n```\r\n\r\n### 3. Forecast Scenarios\r\n```python\r\nscenarios = analyzer.forecast_completion()\r\nfor name, scenario in scenarios.items():\r\n    print(f\"{scenario.name}: ${scenario.total_forecast:,.0f}\")\r\n```\r\n\r\n## Resources\r\n- **DDC Book**: Chapter 3.1 - Cost Management\r\n- **Reference**: PMI Cost Management\r\n",{"slug":5,"description":7,"display_name":30},"Budget Variance Analyzer","main","e7e336ac628c3e3bd771aff1aaa469c93778f94a","skills\u002Fdatadrivenconstruction\u002Fbudget-variance-analyzer",0,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del","2026-08-23 22:39:37",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add kbarbel640-del\u002Fskills --skill budget-variance-analyzer",{"tool":44,"command":45},"bunx","bunx skills add kbarbel640-del\u002Fskills --skill budget-variance-analyzer",{"tool":47,"command":48},"pnpm","pnpm dlx skills add kbarbel640-del\u002Fskills --skill budget-variance-analyzer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fbudget-variance-analyzer\u002FSKILL.md",true,[52],{"path":53,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":56,"sourceHtmlUrl":57},"_meta.json","REFERENCE","参考文档",316,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fdatadrivenconstruction\u002Fbudget-variance-analyzer\u002F_meta.json",[59,85,108,126,131,151],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":25},"01M6G8J55967D6281ACMKAKTEQ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84],"crowd prompting","prompting","api","with","tokens","domain","world","prompts","operations","instructions","text","tool","system","improve","productivity","marketplace","https","content","ai agents",{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":25},"01M6G8J0PKPAYVET6BWE8W4C26","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[92,68,93,22,94,95,96,97,98,99,100,101,102,103,104,105,106,73,107],"dilemm ai","arena","browser","openclaw agent","create","automation","browser automation","bot","openclaw","design","strategy","headless","compete","submit","matchmaking","use",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":25},"01M6G8HWAF3K9SW7NP3Z83CPJ6","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, and submit comments. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, or submitting paper reviews via API at http:\u002F\u002F150.158.152.82:8000.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Fweak-accept\u002FSKILL.md",[],[115,116,117,118,119,120,121,69,122,105,107,123,68,124,125],"arxiv paper reviews","reviews","arxiv","paper","crawler","papers","comments","fetch","read","http","via",{"skillNo":127,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":25},"01M6G8HQJ7N7WMY6YV7D7SSJ16","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[118,117,116,115,125,120,121,69,119,105,107,122,123,68,124],{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":137,"publishedAt":25},"01M6G8HM95Y64JNVFC2HN4E2BG","git-summary","Get a quick summary of the current Git repository including status, recent commits, branches, and contributors.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzweack\u002Fgit-summary\u002FSKILL.md",[],[138,139,140,141,142,143,144,145,146,147,148,149,150],"git","summary","git summary","commits","repository","win32","status","linux","contributors","true","quick","get","branches",{"skillNo":152,"name":153,"nameZh":6,"description":154,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":155,"categories":156,"keywords":157,"publishedAt":25},"01M6G8HGEGF05CNEJCGVYFSC4R","agent-constitution","Interact with AgentConstitution governance contracts on Base Sepolia. Check compliance, read rules, log actions, query governance state.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fztsalexey\u002Fagent-constitution\u002FSKILL.md",[],[158,159,160,161,69,162,163,31,164,123,165,166,167,168,169,82,170,171,172],"agent constitution","constitution","contracts","tree","query","base","log","check","Rules","projects","compliance","actions","state","governance","github"]