How the financial_rigor.py Tool Works in the AI Berkshire Project: A Complete Technical Guide
The financial_rigor.py tool is a zero-dependency command-line toolkit that enforces exact decimal arithmetic for financial validation, providing six sub-commands for market-cap verification, valuation metrics, cross-source validation, Benford's Law checks, exact calculations, and three-scenario valuation within the ai-berkshire research workflow.
The financial_rigor.py module serves as the numerical backbone of the ai-berkshire repository, ensuring every financial figure used in investment research is computed with precision and auditable methodology. Located at tools/financial_rigor.py, this self-contained Python script operates without external dependencies, making it executable in any isolated Python 3.7+ environment. It functions as a validation gate that cross-checks data integrity before figures enter the project's analytical pipeline.
Core Architecture and Design Philosophy
Zero-Dependency Standard Library Implementation
Unlike typical financial tools that rely on NumPy or Pandas, financial_rigor.py imports only from the Python standard library. At lines 18-22, the module loads argparse, json, math, sys, and decimal—nothing else. This design choice ensures reproducible research pipelines that can run in sandboxed environments without package management conflicts.
Exact Decimal Arithmetic Engine
The tool initializes a high-precision decimal.Context at lines 28-29 with 28-digit precision and round-half-even rounding mode. This eliminates floating-point drift that commonly corrupts financial calculations involving large market capitalizations or split-adjusted share counts.
The helper function exact() (lines 31-38) converts any numeric input—whether int, float, or str—into a Decimal safely while preserving precision. This ensures that values like 9.11e9 shares are handled exactly as 9,110,000,000 rather than approximations.
Validation Sub-Commands and Functions
The CLI exposes six distinct sub-commands through an argparse sub-parser configuration (lines 67-86). Each command targets a specific financial validation scenario.
Market-Cap Verification
The verify-market-cap command (implementation at lines 61-92) validates whether price × shares matches a reported market capitalization. It accepts --price, --shares, --reported, and --currency arguments. The logic flags deviations exceeding 5% as errors and deviations exceeding 1% as cautions, outputting a bordered report with status icons (✅, ⚠️, or ❌).
Valuation Metrics Calculation
The verify-valuation routine (lines 98-161) computes exact PE ratios, PB ratios, ROE, P/FCF, dividend yields, and PS ratios using the decimal engine. All calculations avoid floating-point intermediates, ensuring that derived metrics reflect true arithmetic precision.
Cross-Source Data Validation
The cross-validate command (lines 66-104) receives a JSON dictionary mapping sources to values, calculates a median consensus, and reports any source deviating beyond a configurable tolerance (default 2%). This function is critical for reconciling discrepancies between data vendors like Yahoo Finance, Bloomberg, and annual reports.
Benford's Law Statistical Check
To detect potential data manipulation or anomalies, the benford command (lines 112-162) performs a chi-squared test against expected first-digit distributions. This statistical rigor helps identify synthetic or manipulated financial datasets before they contaminate research.
Exact Expression Calculator
The calc command (lines 88-114) provides a sandboxed arithmetic evaluator that accepts expressions containing only numbers and operators (+, -, *, /, ( , )). It prints the exact decimal result, preventing the subtle rounding errors inherent in standard Python REPL calculations.
Three-Scenario Valuation Projections
The three-scenario command (lines 120-146) projects target prices under optimistic, base, and pessimistic assumptions. It accepts --eps, --growth (three rates), --pe (three multiples), --years, and --shares parameters, then computes scenario-specific valuations using exact decimal arithmetic throughout the projection chain.
CLI Integration and Automation
The tool integrates into the ai-berkshire automation layer via scripts/sync-codex-skills.py (line 78), where Claude Code skills invoke the toolkit at validation checkpoints. This automatic invocation ensures that human researchers cannot bypass numerical verification before finalizing reports.
Output formatting utilizes the fmt_number function (lines 40-55) to convert large Decimal values into human-readable units (亿/万亿/B/T), making audit trails comprehensible while preserving raw decimal values for downstream machine parsing.
Usage Examples
Command-Line Interface
Verify market capitalization for a Hong Kong-listed security:
python3 tools/financial_rigor.py verify-market-cap \
--price 510 --shares 9.11e9 --reported 4.65e12 --currency HKD
Run a three-scenario valuation analysis:
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
Programmatic Python Integration
Import functions directly into research scripts:
from tools.financial_rigor import verify_market_cap, cross_validate
# Validate market cap with exact decimals
verify_market_cap(
price=510,
shares=9.11e9,
reported_cap=4.65e12,
currency='HKD'
)
# Cross-validate revenue figures across sources (units in 亿)
field = "revenue"
source_vals = {
"AnnualReport": 7518,
"Yahoo": 7500,
"StockAnalysis": 7520
}
cross_validate(field, source_vals, unit="亿")
Summary
- The
financial_rigor.pytool operates as a zero-dependency validator using only Python's standard library (decimal,argparse,json). - It enforces 28-digit precision decimal arithmetic via a custom
Contextandexact()helper function to eliminate floating-point errors. - Six sub-commands (
verify-market-cap,verify-valuation,cross-validate,benford,calc,three-scenario) provide comprehensive financial validation. - The tool auto-invokes via
scripts/sync-codex-skills.pyto enforce validation gates in the research workflow. - All output includes human-readable formatting (亿/万亿 units) alongside exact decimal values for auditability.
Frequently Asked Questions
What makes financial_rigor.py different from standard financial calculators?
Unlike calculators relying on floating-point arithmetic, financial_rigor.py uses the decimal module with 28-digit precision and round-half-even rounding. This prevents the accumulation of rounding errors common when processing large market caps or precise EPS figures, ensuring that price × shares calculations match reported values exactly.
How does the cross-validation feature handle conflicting data sources?
The cross-validate command calculates a median consensus from input sources and flags any value deviating beyond the default 2% tolerance. It generates a detailed report showing each source's variance from the median, allowing researchers to identify outliers in data from Annual Reports, Yahoo Finance, or Bloomberg terminals.
Can financial_rigor.py be used outside the ai-berkshire project?
Yes. Because the tool has no external dependencies, it can function as a standalone validator in any Python 3.7+ environment. Simply copy tools/financial_rigor.py to your project and invoke it via CLI or import its functions directly into other financial analysis workflows.
Why does the tool use 28-digit precision decimal arithmetic?
The 28-digit precision specified in decimal.Context (lines 28-29) accommodates the full range of financial magnitudes encountered in global equity markets, from fractional share prices to trillion-dollar market capitalizations. This precision ensures that intermediate calculations in multi-step valuations (like the three-scenario projections) never lose significant digits that could distort final target prices.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →