# How AI Berkshire Ensures Financial Data Accuracy with Its Tool Layer

> Discover how AI Berkshire ensures financial data accuracy using its Tool Layer. Explore exact decimal arithmetic, cross-source validation, and Benford's Law analysis for verifiably precise financial figures.

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

---

**AI Berkshire ensures financial data accuracy through a dedicated Tool Layer in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py), a zero-dependency Python toolkit that performs exact-decimal arithmetic, cross-source validation, and Benford-law analysis to verify every financial figure before publication.**

The `xbtlin/ai-berkshire` repository implements a rigorous validation pipeline to guarantee financial data accuracy at every stage of its research workflow. At the center of this system lies the **Tool Layer**, a self-contained collection of validation utilities located in the `tools/` package. This lightweight, std-lib-only toolkit performs deterministic calculations and multi-source cross-checks, embedding reproducible audit trails directly into AI-generated financial reports.

## Exact-Decimal Arithmetic Eliminates Floating-Point Drift

Financial calculations require precision that standard IEEE-754 floating-point arithmetic cannot guarantee. In [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) (lines 28-31), the **Exact-Decimal Engine** initializes a `decimal.Context` with 28-digit precision and **ROUND_HALF_EVEN** rounding mode. This ensures that repetitive operations—such as compounding interest or currency conversions—do not accumulate microscopic drifts that could distort billion-dollar valuations.

All downstream calculations in the Tool Layer inherit this context, guaranteeing that every multiplication, division, and aggregation produces identical results across Python versions and operating systems.

## Automated Verification of Market Capitalization and Valuation Metrics

The Tool Layer automatically validates canonical financial relationships to catch data entry errors and API anomalies before they propagate into research reports.

### Market-Cap Integrity Checks

The `verify-market-cap` command (lines 61-90) recomputes market capitalization from price and shares outstanding, then compares the result against reported values. The system flags deviations greater than **5%** as hard errors and deviations greater than **1%** as warnings. This arithmetic check uses the exact-decimal engine to ensure that `price × shares` matches the reported market cap to the last cent.

### Valuation Ratio Calculations

The `verify-valuation` routine (lines 98-160) computes standard metrics—**PE, PB, ROE, P/FCF, dividend yield, and PS**—using exact decimal arithmetic. Each metric is printed in an audit-ready block demarcated by `=` lines, creating a transparent paper trail that reviewers can trace back to the raw inputs.

## Cross-Source Data Validation and Consensus Building

Modern financial data often arrives from disparate providers with conflicting figures. The `cross-validate` command (lines 163-205) accepts a JSON map of values from different sources, calculates a median reference point, and reports per-source deviation against a configurable tolerance (default **2%**).

When discrepancies exceed the threshold, the tool automatically suggests the most reliable consensus value. This prevents AI models from cherry-picking favorable outliers and forces explicit acknowledgment of data uncertainty in the final report.

## Statistical Fraud Detection via Benford's Law

To surface potential data fabrication or manipulation, the Tool Layer implements a **Benford-Law Check** (lines 208-281). The `benford` command analyzes the frequency distribution of leading digits in a series of financial numbers, calculating the Mean Absolute Deviation (MAD) and χ² statistics.

Real-world financial data typically conforms to Benford's Law; fabricated or manipulated datasets often deviate significantly. The tool reports conformity status, providing a red-flag mechanism for analysts reviewing automated financial statements.

## Exact Calculator and Scenario Modeling

### Sandbox-Safe Arithmetic

The `calc` command (lines 284-313) evaluates arbitrary arithmetic expressions using the same exact-decimal engine. The parser is sandboxed to allow only numbers and operators, preventing injection attacks while giving researchers a reliable way to verify ad-hoc calculations outside the main workflow.

### Three-Scenario Valuation Projections

For equity research, the `three-scenario` command (lines 316-380) projects price targets under **optimistic, neutral, and pessimistic** assumptions for growth rates and PE multiples. Each scenario uses exact arithmetic to calculate terminal values, ensuring that the spread between bull and bear cases reflects genuine modeling differences rather than computational artifacts.

## Integration Workflow: From Raw Data to Audited Reports

The Tool Layer integrates with Claude-Code skills through a deterministic four-step pipeline:

1.  **Data Ingestion**: A skill (e.g., [`valuation.md`](https://github.com/xbtlin/ai-berkshire/blob/main/valuation.md) or [`screening.md`](https://github.com/xbtlin/ai-berkshire/blob/main/screening.md)) gathers raw numbers from APIs or CSVs.
2.  **Validation Invocation**: Before publishing findings, the skill invokes the appropriate sub-command of [`financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/financial_rigor.py) (e.g., `verify-market-cap`, `cross-validate`).
3.  **Result Capture**: The tool returns a Boolean success flag and/or a dictionary of computed metrics, plus console output.
4.  **Audit Embedding**: The skill incorporates the tool’s human-readable output into the report’s "Data Validation" section.

The [`tools/report_audit.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/report_audit.py) module post-processes skill output to ensure every numeric claim has an accompanying Rigor-tool audit. Meanwhile, [`scripts/sync-codex-skills.py`](https://github.com/xbtlin/ai-berkshire/blob/main/scripts/sync-codex-skills.py) generates the Codex-compatible wrappers that automate these calls.

## Practical Command-Line Usage

Because [`financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/financial_rigor.py) contains only standard-library dependencies, you can execute these validations in any Python 3.7+ environment after cloning the repository:

```bash

# Verify market-cap arithmetic

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

```

```bash

# Check valuation ratios

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

```

```bash

# Cross-validate revenue from multiple providers

python3 tools/financial_rigor.py cross-validate \
    --field revenue \
    --values '{"AnnualReport": 7518, "Yahoo": 7500, "Wind": 7520}' \
    --unit 亿 \
    --tolerance 2.0

```

```bash

# Benford-law sanity check

python3 tools/financial_rigor.py benford \
    --values '[1234, 2345, 3456, 4567, 5678]'

```

```bash

# Exact arithmetic calculation

python3 tools/financial_rigor.py calc \
    --expr '510 * 9.11e9'

```

```bash

# Three-scenario valuation model

python3 tools/financial_rigor.py three-scenario \
    --price 510 \
    --eps 23.5 \
    --shares 9.11 \
    --growth 0.15 0.08 0.00 \
    --pe 25 20 15 \
    --years 3 \
    --currency HKD

```

Each command outputs a detailed audit block that surrounding automation captures for inclusion in the final research report.

## Key Files in the Tool Layer

-   **[`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py)**: The core validation engine containing exact-decimal arithmetic, market-cap verification, valuation metrics, cross-source validation, Benford analysis, and scenario modeling.
-   **[`tools/report_audit.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/report_audit.py)**: Post-processor that enforces the presence of validation audits in skill outputs.
-   **[`scripts/sync-codex-skills.py`](https://github.com/xbtlin/ai-berkshire/blob/main/scripts/sync-codex-skills.py)**: Generates skill wrappers that automatically invoke the Tool Layer at critical checkpoints.
-   **`skills/*.md`**: Human-readable skill specifications (e.g., [`valuation.md`](https://github.com/xbtlin/ai-berkshire/blob/main/valuation.md)) that embed calls to [`financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/financial_rigor.py).

## Summary

-   **Exact-Decimal Engine**: Uses `decimal.Context` with 28-digit precision and `ROUND_HALF_EVEN` to eliminate floating-point drift in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) (lines 28-31).
-   **Automated Cross-Checks**: Verifies that `price × shares` matches reported market cap within 1-5% tolerance (lines 61-90).
-   **Multi-Source Consensus**: Validates data against median references from multiple providers with configurable tolerance (lines 163-205).
-   **Fraud Detection**: Applies Benford's Law analysis to detect anomalous digit distributions (lines 208-281).
-   **Reproducible Audits**: Every validation prints a human-readable, `=` demarcated audit block that embeds directly into research reports.
-   **Zero-Dependency Design**: Pure Python 3.7+ standard library ensures identical behavior across all environments.

## Frequently Asked Questions

### What is the Tool Layer in AI Berkshire?

The **Tool Layer** is a validation subsystem located in the `tools/` package of the `xbtlin/ai-berkshire` repository. It is a zero-dependency Python toolkit that performs deterministic financial calculations and data integrity checks. Claude-Code skills invoke this layer automatically before finalizing reports to ensure every numeric claim is traceable to a reproducible computation.

### Why does financial_rigor.py use decimal arithmetic instead of float?

Standard floating-point arithmetic introduces rounding errors that compound over financial calculations. The `decimal` module (configured at lines 28-31 of [`financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/financial_rigor.py)) provides arbitrary precision and explicit rounding modes like `ROUND_HALF_EVEN`, ensuring that valuations, ratios, and cross-multiplications remain accurate to the penny regardless of computation order or environment.

### How does cross-source validation handle conflicting data?

The `cross-validate` command (lines 163-205) accepts a JSON map of values from different providers, calculates a median reference, and flags deviations exceeding a configurable tolerance (default 2%). If sources disagree significantly, the tool suggests the consensus median and forces the skill to acknowledge the discrepancy in the final report, preventing silent reliance on potentially erroneous single sources.

### What is the purpose of the Benford-Law check?

The `benford` command (lines 208-281) performs a statistical distribution test on financial numbers to detect potential data fabrication or manipulation. Natural financial data typically follows Benford's Law (logarithmic distribution of leading digits); fabricated data often deviates. The tool reports MAD and χ² statistics, providing a red-flag mechanism for analysts to investigate suspicious datasets before publication.