financial_rigor.py Analysis: Exact-Decimal Validation for Investment Research

The financial_rigor.py analysis serves as the core Financial Rigor Toolkit for the AI-Berkshire project, providing programmatic, exact-decimal validation of financial data through zero-dependency Python functions that eliminate floating-point drift and ensure audit-ready calculations.

The financial_rigor.py analysis is the backbone of the AI-Berkshire repository's data integrity strategy. Located at tools/financial_rigor.py, this tool ensures that every financial figure used in investment research undergoes rigorous, reproducible validation using exact arithmetic rather than floating-point approximations. It is deliberately invoked by Claude-Code skills to guarantee that no LLM "mental math" is trusted; every key numeric result must pass through this rigor engine.

Core Architecture and Design Principles

The financial_rigor.py analysis relies exclusively on the Python standard library—specifically decimal, json, math, and argparse—maintaining zero external dependencies. At the top of tools/financial_rigor.py (lines 2-9), the script establishes a high-precision Decimal context (_CTX) that prevents floating-point drift, ensuring that calculations like price × shares match reported market caps exactly without IEEE 754 approximation errors.

The tool operates as a CLI entry point with sub-commands defined in the docstring (lines 10-15), making it accessible both to automated skill workflows and manual verification. This design centralizes all financial mathematics in a single, well-tested script, reducing the risk of divergent implementations across different research skills.

Key Validation Functions

Market-Cap Verification (verify_market_cap)

The verify_market_cap function (lines 61-90) performs the fundamental sanity check that price × shares = reported market cap. It accepts --price, --shares, and --reported parameters, calculates the implied market capitalization using exact Decimal arithmetic, and flags any deviation exceeding 5%. This catches common data entry errors where share counts or price quotes use different units (e.g., billions vs. millions).

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

Valuation Metrics (verify_valuation)

The verify_valuation function calculates critical investment ratios—PE, PB, ROE, P/FCF, dividend yield, and PS—using exact decimals to avoid compounding rounding errors. Located at lines 98-161 in tools/financial_rigor.py, this function takes raw inputs like --eps, --bvps, and --fcf-per-share and outputs standardized multiples with clear audit trails.

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

Cross-Source Validation (cross_validate)

The cross_validate function (lines 67-99) addresses data quality issues by comparing values from multiple sources. It accepts a JSON dictionary of values (e.g., {"年报": 7518, "Yahoo": 7500, "StockAnalysis": 7520}), computes a median consensus, and highlights any source deviating beyond a specified tolerance percentage. This ensures that discrepancies between financial data providers are caught before they contaminate research reports.

python3 tools/financial_rigor.py cross-validate \
    --field revenue \
    --values '{"年报": 7518, "Yahoo": 7500, "StockAnalysis": 7520}' \
    --unit 亿

Benford's Law Analysis (benford_check)

The benford_check function (lines 108-165) implements Benford's Law to detect possible data fabrication or manipulation. It analyzes the distribution of leading digits in a dataset and compares them against the expected logarithmic frequencies (e.g., ~30% of numbers should start with 1). Significant deviations may indicate artificial data generation or accounting irregularities.

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

Exact Calculator (exact_calc)

The exact_calc function (lines 88-111) provides a safe arithmetic evaluator that processes expressions with decimal precision. Unlike standard Python calculators that suffer from floating-point representation issues (e.g., 0.1 + 0.2 ≠ 0.3), this function guarantees exact results for financial calculations involving large numbers or precise ratios.

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

Three-Scenario Valuation (three_scenario_valuation)

The three_scenario_valuation function (lines 120-166) projects EPS growth under optimistic, neutral, and pessimistic scenarios, then computes target prices using user-specified PE multiples. This强制要求 (mandates) systematic scenario analysis rather than single-point estimates, requiring explicit inputs for growth rates and valuation multiples across three distinct time horizons.

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

Integration with AI-Berkshire Skills

The financial_rigor.py analysis is not a standalone tool but an integrated component of the AI-Berkshire workflow. According to skills/investment-research.md (lines 57-83), Claude-Code skills automatically invoke these verification functions during data collection. Similarly, skills/thesis-drift.md enforces strict use of financial_rigor.py for all numeric transformations, ensuring that research reports maintain reproducible, traceable calculations.

All outputs are human-readable and audit-ready, printing clear summaries, deviation percentages, and consensus values. This integration guarantees that stock screeners, portfolio reviews, and investment theses all derive from identically calculated, cross-validated figures.

Summary

  • Exact decimal arithmetic eliminates floating-point drift through a high-precision Decimal context (_CTX) defined in tools/financial_rigor.py lines 2-9.
  • Automated verification ensures market-cap calculations match reported values within 5% tolerance via verify_market_cap.
  • Cross-source validation identifies data discrepancies by computing median consensus across multiple financial data providers.
  • Fraud detection applies Benford's Law analysis to detect potential data fabrication in financial datasets.
  • Scenario analysis enforces disciplined three-case valuation (optimistic/neutral/pessimistic) through three_scenario_valuation.

Frequently Asked Questions

What is the primary purpose of the financial_rigor.py analysis?

The financial_rigor.py analysis provides programmatic, exact-decimal validation of financial data used in investment research. It ensures that calculations like market capitalization, valuation multiples, and growth projections are computed with precision rather than floating-point approximations, serving as the single source of truth for all numeric operations in the AI-Berkshire project.

How does financial_rigor.py prevent calculation errors in investment research?

The tool uses Python's decimal module with a custom high-precision context (_CTX) to avoid IEEE 754 floating-point errors. Functions like exact_calc and verify_valuation process all inputs as Decimal objects, ensuring that operations like multiplication and division maintain exact precision. The script also cross-validates data across multiple sources using cross_validate to catch input discrepancies before they affect calculations.

Which CLI commands does financial_rigor.py support?

The analysis supports six primary sub-commands: verify-market-cap (validates price × shares), verify-valuation (calculates PE, PB, ROE ratios), cross-validate (compares multi-source data), benford (detects anomalous digit distributions), calc (exact arithmetic evaluator), and three-scenario (multi-case valuation projections). Each command accepts specific parameters like --price, --eps, or --growth and outputs human-readable, audit-ready results.

How does the Benford's law check work in financial_rigor.py?

The benford_check function analyzes the frequency distribution of leading digits in a provided dataset (e.g., revenue figures or trading volumes) and compares them against Benford's expected logarithmic distribution. If the actual distribution deviates significantly from the expected 30.1% for digit 1, 17.6% for digit 2, etc., the function flags potential data manipulation or fabrication, providing a statistical safeguard against artificial data generation.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →