# How the portfolio-review Skill Optimizes Allocation and Rebalancing in AI-Berkshire

> Discover how the portfolio-review skill optimizes allocation and rebalancing in AI-Berkshire. It uses a six-stage workflow to generate data-driven trade recommendations and analyze risks.

- Repository: [Xbt Lin/ai-berkshire](https://github.com/xbtlin/ai-berkshire)
- Tags: deep-dive
- Published: 2026-07-03

---

**The portfolio-review skill transforms raw holding lists into data-driven rebalancing recommendations through a six-stage workflow that normalizes input, validates valuations with exact decimal arithmetic, scores position health, analyzes portfolio-level risks, and outputs an executable trade matrix.**

The **`portfolio-review`** skill in the [xbtlin/ai-berkshire](https://github.com/xbtlin/ai-berkshire) repository is a modular AI workflow defined in **[[`skills/portfolio-review.md`](https://github.com/xbtlin/ai-berkshire/blob/main/skills/portfolio-review.md)](https://github.com/xbtlin/ai-berkshire/blob/main/skills/portfolio-review.md)**. It integrates with **[[`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py)](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py)** to provide rigorous, auditable portfolio management that eliminates floating-point drift and surfaces hidden concentration risks.

## Six-Stage Optimization Architecture

The skill processes holdings through six distinct layers, each implemented as a specific block in the Markdown-defined workflow.

### Stage 1: Parsing and Normalisation

The skill first reads user-supplied holding strings—whether formatted as percentages, share counts, or the shortcut `我的持仓`—and constructs a canonical table.

In **[[`skills/portfolio-review.md`](https://github.com/xbtlin/ai-berkshire/blob/main/skills/portfolio-review.md)](https://github.com/xbtlin/ai-berkshire/blob/main/skills/portfolio-review.md)** (lines 26‑48), the parsing logic standardizes entries into columns: `标的 | 代码 | 持仓量 | 成本价 | 现价 | 市值 | 占比 | 盈亏`. If a previous report exists at [`reports/portfolio-latest.md`](https://github.com/xbtlin/ai-berkshire/blob/main/reports/portfolio-latest.md), the skill merges that data (line 35) to maintain continuity.

### Stage 2: Live Data Refresh via Background Agent

Once normalized, the skill fires a **Task**-based background Agent that executes parallel **WebSearch** jobs for every ticker.

As described in the “获取最新数据” block (lines 51‑58), each job collects:
- Latest price and valuation multiples
- Quarterly financial changes
- Recent news and events
- Analyst consensus estimates

This ensures the optimization reacts to real-time price swings and earnings releases.

### Stage 3: Exact-Decimal Valuation Validation

For each position, the skill invokes **`tools/financial_rigor.py verify-valuation`** to compute **PE**, **PB**, **P/FCF**, and dividend yield using exact `Decimal` arithmetic.

The call site appears at line 59 of the skill file, while the implementation resides in **[[`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py)](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py)** (lines 98‑60). Results receive **A/B/C ratings**; C-rated items get flagged with low-confidence tags to prevent optimization drift from imprecise inputs.

### Stage 4: Single-Position Health Check

The skill generates a concise “仓位建议” table (lines 61‑68) displaying PE, logic changes, health scores, and recommendations.

It also poses three binary questions to surface hidden risks:
1. Would you buy this position again today?
2. Are you comfortable holding for 5 years?
3. Is your investment thesis complete?

These qualitative checks feed into a binary “是否继续持有” flag that overrides purely quantitative signals when necessary.

### Stage 5: Portfolio-Level Risk Analysis

This stage evaluates the entire portfolio through four lenses:

- **Concentration checks** (lines 79‑86): Monitors largest-holding percentage, top‑3 concentration range, total position count, and cash reserves.
- **Correlation mapping** (lines 92‑106): Builds an implicit network of sector and country exposures, running threshold checks to detect overlapping risks.
- **Opportunity-cost ranking** (lines 106‑110): Ranks holdings by **预期年化回报** using the formula `预期年化 ≈ FCF Yield + 预期增速`, calculated via `tools/financial_rigor.py three-scenario`.
- **Stress-testing** (lines 127‑134): Runs qualitative scenario impact tables for global recession, US‑China conflict, rate spikes, and tech bubbles to estimate max drawdown.

The three-scenario valuation logic is implemented in **[[`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py)](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py)** (lines 20‑59) within the `three_scenario_valuation` function.

### Stage 6: Actionable Rebalancing Output

The final layer synthesizes all signals into a **调仓建议** matrix (lines 41‑55) categorizing each position as:
- **加仓** (Increase)
- **减仓** (Decrease)
- **清仓** (Liquidate)
- **新建仓** (New Position)
- **不动** (Hold)

Each recommendation includes target percentages and rationale. If any holding underperforms cash, the skill suggests using `/industry-research` or `/investment-checklist` to find alternatives. The skill persists the updated report to [`reports/portfolio-latest.md`](https://github.com/xbtlin/ai-berkshire/blob/main/reports/portfolio-latest.md) (lines 74‑80) for stateful tracking.

## Core Optimization Mechanisms

### Three-Scenario Opportunity Cost Model

The ranking engine calculates expected annual returns through a conservative three-scenario framework. Rather than relying on single-point estimates, the model calculates intrinsic value across optimistic, neutral, and pessimistic growth and PE assumptions, preventing over-optimization to bullish outliers.

### Exact-Decimal Arithmetic

All valuation comparisons use `Decimal` types rather than floating-point numbers. This eliminates micro-drift when comparing small deviation thresholds (such as the 5 % market-cap tolerance in `verify_market_cap`), ensuring rebalancing triggers fire only on economically meaningful moves.

### Persistent State Management

By reading from and writing to [`reports/portfolio-latest.md`](https://github.com/xbtlin/ai-berkshire/blob/main/reports/portfolio-latest.md), the skill maintains an audit trail across sessions. Users can override suggested allocations at any stage while retaining the data lineage—every numeric cell traces back to a live API call or verified valuation routine.

## Implementation Examples

### Command-Line Invocation

Trigger the optimization workflow via slash command:

```markdown
/portfolio-review 腾讯30%, 美团20%, 茅台20%, 英伟达15%, 现金15%

```

The command forwards `$ARGUMENTS` to the **Codex** adapter at **[[`codex-skills/portfolio-review/SKILL.md`](https://github.com/xbtlin/ai-berkshire/blob/main/codex-skills/portfolio-review/SKILL.md)](https://github.com/xbtlin/ai-berkshire/blob/main/codex-skills/portfolio-review/SKILL.md)**, which injects the arguments into the canonical workflow.

### Programmatic Three-Scenario Valuation

Call the ranking engine directly from Python:

```python
from tools.financial_rigor import three_scenario_valuation

# Price, EPS, and shares in billions (亿)

price = 510.0
eps = 23.5
shares = 9.11

# Scenarios: optimistic, neutral, pessimistic

growth = (0.15, 0.08, 0.00)
pe = (25, 20, 15)

three_scenario_valuation(
    current_price=price,
    current_eps=eps,
    shares_billion=shares,
    growth_optimistic=growth[0],
    growth_neutral=growth[1],
    growth_pessimistic=growth[2],
    pe_optimistic=pe[0],
    pe_neutral=pe[1],
    pe_pessimistic=pe[2],
    years=3,
    currency="HKD"
)

```

This reproduces the “机会成本分析” step (lines 106‑110), generating target-price scenarios that feed the portfolio ranking matrix.

### Manual Valuation Verification

Validate individual metrics from the terminal:

```bash
python3 tools/financial_rigor.py verify-valuation \
    --price 510 \
    --eps 23.5 \
    --bvps 120 \
    --fcf-per-share 18 \
    --dividend 2.4

```

The output mirrors the valuation table in step 3 (lines 59‑66), providing A/B/C grades based on exact-decimal calculations.

## Summary

- The **portfolio-review skill** operates as a six-stage pipeline defined in [`skills/portfolio-review.md`](https://github.com/xbtlin/ai-berkshire/blob/main/skills/portfolio-review.md), transforming raw holdings into optimized rebalancing plans.
- **Exact-decimal arithmetic** in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) eliminates floating-point errors during valuation comparisons.
- **Three-scenario analysis** (`three_scenario_valuation`) ranks holdings by conservative expected returns rather than speculative price targets.
- **Portfolio-level checks** expose concentration risks, correlation networks, and stress-test vulnerabilities before trades execute.
- **Stateful persistence** via [`reports/portfolio-latest.md`](https://github.com/xbtlin/ai-berkshire/blob/main/reports/portfolio-latest.md) maintains auditability across optimization runs.

## Frequently Asked Questions

### How does the skill handle different input formats like percentages or share counts?

The parsing layer (lines 26‑48 of [`skills/portfolio-review.md`](https://github.com/xbtlin/ai-berkshire/blob/main/skills/portfolio-review.md)) normalizes all inputs—whether percentages, absolute share counts, or the Chinese shorthand `我的持仓`—into a canonical table structure. This ensures downstream calculations receive consistent data shapes regardless of how the user submits their holdings.

### Why does the skill use Decimal arithmetic instead of standard floats?

Standard floating-point arithmetic introduces micro-drift that can trigger false rebalancing signals when comparing small thresholds (e.g., 5 % market-cap deviations). The `verify_valuation` function in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) uses `Decimal` types to maintain precision through chained calculations, ensuring the optimization responds only to economically significant changes.

### What happens if a position receives a C-rating during valuation?

C-rated positions receive a low-confidence tag that flags them for heightened scrutiny during the health-check stage. The skill will still include them in the opportunity-cost ranking, but may recommend using companion skills like `/industry-research` to find alternatives if the position underperforms cash-on-hand expectations.

### Can users override the rebalancing recommendations?

Yes. The modular architecture allows intervention at any stage, and the skill maintains an audit trail by persisting state to [`reports/portfolio-latest.md`](https://github.com/xbtlin/ai-berkshire/blob/main/reports/portfolio-latest.md). Users can modify target allocations or thesis answers while retaining the underlying data lineage for transparency.