# Market Cap Verification in AI Berkshire: How It Detects Financial Data Errors

> Discover how AI Berkshire's market cap verification detects financial data errors using exact decimal arithmetic. Learn more about its accuracy.

- Repository: [Xbt Lin/ai-berkshire](https://github.com/xbtlin/ai-berkshire)
- Tags: how-to-guide
- Published: 2026-07-05

---

**AI Berkshire's `verify_market_cap` function uses exact decimal arithmetic to validate reported market capitalizations against calculated values, flagging discrepancies above 1% to catch stale data or currency mismatches.**

The `xbtlin/ai-berkshire` repository provides a specialized *Financial-Rigor* toolkit designed to prevent downstream valuation errors through automated data-quality checks. At its core, the `verify_market_cap` routine in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) performs high-precision verification of reported market cap figures against independent calculations derived from share price and shares outstanding.

## How Market Cap Verification Works in AI Berkshire

The verification process follows a rigorous five-step pipeline that eliminates floating-point errors and provides clear visual feedback for analysts.

### Exact Decimal Arithmetic Conversion

All monetary inputs undergo conversion to `Decimal` objects via the internal `exact()` helper function. According to the source code in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) (lines 31-38), this conversion prevents standard floating-point rounding errors that could mask small but significant mismatches in billion-dollar calculations.

### High-Precision Recalculation

The system recomputes market capitalization using the high-precision context `_CTX` defined in the module. As implemented in lines 63-68, the calculation follows the standard formula:

```python
calculated = price × shares

```

This operation maintains exact precision throughout the computation, avoiding the cumulative rounding errors typical of float-based financial calculations.

### Deviation Measurement and Threshold Analysis

The routine computes percentage deviation between calculated and reported values using the formula found in lines 68-69:

```python
deviation = abs(float(calculated - reported) / float(reported)) * 100

```

If the reported cap equals zero, the deviation defaults to 0 to prevent division errors.

### Three-Tier Alert System

The implementation applies distinct verification thresholds based on deviation magnitude:

- **> 5% deviation** – Emits a hard warning (`❌`) prompting immediate investigation of three common error sources: stale share-count data, mismatched currency units, or outdated price quotes (lines 80-85)
- **1% – 5% deviation** – Displays a cautionary notice (`⚠️`) indicating tolerable gaps often caused by normal price swings or recent share-issuance events (lines 86-88)
- **≤ 1% deviation** – Returns a success confirmation (`✅`) verifying numerical consistency (lines 89-91)

### Human-Readable Output Formatting

The `fmt_number` helper (lines 40-55) formats large numerical values using scale suffixes (e.g., "万亿" for trillions, "B" for billions, "T" for trillions), enabling rapid visual inspection of discrepancies between calculated and reported figures.

## Common Data Quality Issues Detected

Through exact-decimal computation and clear deviation thresholds, the verification catches typical financial data errors:

- **Out-of-date share counts** occurring after buy-backs or new equity issuances
- **Currency-unit mismatches** between HKD, CNY, and USD denominated values
- **Stale price quotes** resulting from confusion between closing prices and intraday valuations

These checks create a fast, reproducible sanity-check that prevents error propagation into downstream valuation models.

## Implementation Details in tools/financial_rigor.py

The core logic resides in the `verify_market_cap` function spanning lines 61-92 of [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py). The function signature accepts price, shares, reported capitalization, and currency parameters, returning a boolean indicating whether the deviation falls within acceptable limits (≤ 5%).

The module maintains strict separation between calculation logic and presentation formatting, allowing both programmatic API access and command-line usage without code duplication.

## Usage Examples

### Command-Line Interface

Execute market cap verification directly from the terminal using the `verify-market-cap` subcommand:

```bash

# Verify a Hong Kong-listed firm with price HKD 510, 9.11 billion shares,

# and reported market cap of HKD 4.65 trillion

python3 tools/financial_rigor.py verify-market-cap \
    --price 510 \
    --shares 9.11e9 \
    --reported 4.65e12 \
    --currency HKD

```

### Python API

Integrate verification into analytical workflows by importing the function directly:

```python
from tools.financial_rigor import verify_market_cap

# Example values for a Hong Kong-listed security

price = 510                # HKD per share

shares = 9.11e9           # total shares outstanding

reported_cap = 4.65e12    # HKD reported market cap

# Returns True if deviation ≤ 5%, raises warning if > 5%

ok = verify_market_cap(price, shares, reported_cap, currency="HKD")
if not ok:
    raise ValueError("Market-cap mismatch detected – investigate data sources.")

```

Both methods produce structured terminal output displaying price, share count, calculated cap, reported cap, and percentage deviation with appropriate status indicators.

## Summary

- **Exact decimal arithmetic** via the `exact()` helper eliminates floating-point errors that could obscure small discrepancies in large-cap calculations.
- **Three-tier threshold system** distinguishes between critical errors (> 5%), cautionary gaps (1-5%), and verified consistency (≤ 1%).
- **Common error detection** identifies stale share counts, currency mismatches, and outdated price data before they corrupt valuation models.
- **Dual interface** supports both CLI scripting and Python API integration through [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py).
- **Human-readable formatting** via `fmt_number` enables rapid visual verification of trillion-scale numerical comparisons.

## Frequently Asked Questions

### What precision does AI Berkshire use for market cap calculations?

AI Berkshire uses Python's `Decimal` type with a custom high-precision context (`_CTX`) rather than standard floating-point numbers. The `exact()` helper in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) converts all inputs to Decimal objects before calculation, eliminating rounding errors that could trigger false positives in billion-dollar market cap verifications.

### Why does the verification flag deviations above 5% as errors?

Deviations exceeding 5% trigger hard warnings (`❌`) because they typically indicate fundamental data errors rather than normal market volatility. According to the source code comments in lines 80-85, these large gaps usually stem from three sources: stale share-count figures (post-buyback), currency unit mismatches (HKD vs. CNY), or incorrectly timestamped price quotes requiring analyst verification.

### Can I use market cap verification programmatically in my Python scripts?

Yes. Import `verify_market_cap` from `tools.financial_rigor` to integrate the check into data pipelines. The function returns a boolean indicating whether the deviation falls within the 5% warning threshold, allowing you to implement conditional logic that raises exceptions or triggers alerts when data quality checks fail.

### How does the formatting helper improve verification readability?

The `fmt_number` function (lines 40-55) automatically scales large numbers using appropriate suffixes such as "万亿" (trillion) for Chinese financial contexts, "B" for billions, and "T" for trillions. This formatting makes it immediately obvious when calculated values (e.g., 4.66T HKD) diverge from reported figures (e.g., 4.65T HKD), reducing the cognitive load during manual review sessions.