How to Use financial_rigor.py for Market Cap Validation in AI-Berkshire
The verify_market_cap function in tools/financial_rigor.py validates market capitalization by comparing calculated price × shares against reported figures, returning a Boolean pass/fail based on a 5% deviation threshold.
The ai-berkshire repository by xbtlin provides rigorous financial validation tools for AI-driven investment research. The financial_rigor.py module serves as the command-line utility for ensuring data integrity, with its market cap validation functionality providing mathematically exact arithmetic to catch discrepancies between calculated and reported valuations.
Understanding the Market Cap Validation Logic
High-Precision Decimal Arithmetic
The script implements an Exact Decimal Engine to eliminate floating-point drift. In tools/financial_rigor.py lines 24-38, the module creates a high-precision context _CTX and defines the exact() helper function. This ensures that all price, share count, and market cap calculations maintain mathematical exactness rather than relying on standard IEEE 754 floating-point operations.
The verify_market_cap Function
Located at lines 61-90, the verify_market_cap() function executes the core validation workflow:
- Converts inputs to
Decimalobjects viaexact()(lines 31-38) - Calculates market cap using exact multiplication:
calculated = _CTX.multiply(p, s)(line 67) - Computes absolute deviation:
abs(float(calculated - r) / float(r)) * 100(line 68) - Returns a Boolean indicating pass/fail based on deviation thresholds
Running Market Cap Validation
Command Line Interface
The script exposes a verify-market-cap subcommand through argparse (lines 67-88). This interface accepts four required arguments: --price, --shares, --reported, and --currency.
Example validation for a Hong Kong-listed security:
python3 tools/financial_rigor.py verify-market-cap \
--price 510 \
--shares 9.11e9 \
--reported 4.65e12 \
--currency HKD
The CLI prints a color-coded report via fmt_number() (lines 40-55), which formats large numbers into human-readable units (亿, 万亿, B, T), and exits with code 0 for pass or 1 for fail.
Programmatic Python Usage
Import the module directly to integrate validation into existing research scripts:
from tools import financial_rigor as fr
# Example: Tencent validation
price = 510 # HKD per share
shares = 9.11e9 # total shares outstanding
reported_cap = 4.65e12 # reported market cap in HKD
# Execute validation
passed = fr.verify_market_cap(price, shares, reported_cap, currency="HKD")
if passed:
print("Market cap validation passed")
else:
print("Market cap validation failed - check for outdated share counts or currency mismatches")
Interpreting Validation Thresholds
The function implements a three-tier tolerance system (lines 80-91):
- ≤ 1% deviation: ✅ Pass (mathematically verified)
- > 1% and ≤ 5% deviation: ⚠️ Acceptable with warning (passes but flags potential data staleness)
- > 5% deviation: ❌ Fail (indicates outdated share counts, currency mismatches, or stale price data)
Integration with AI-Berkshire Workflows
According to the header comments in financial_rigor.py, the tool is designed for automatic invocation by Claude Code skills at critical research checkpoints. The AGENTS.md file documents how these skills interact with the toolkit, while scripts/sync-codex-skills.py generates Codex-compatible wrappers that enforce validation before report publication.
Pseudo-code for skill integration:
def validate_before_report(price, shares, reported_cap, currency):
ok = financial_rigor.verify_market_cap(price, shares, reported_cap, currency)
if not ok:
raise ValueError("Market cap validation failed – aborting skill execution")
return True
Summary
verify_market_capintools/financial_rigor.py(lines 61-90) performs rigorous market cap validation using exact decimal arithmetic- The Exact Decimal Engine (
_CTXandexact()at lines 24-38) prevents floating-point errors in financial calculations - Validation accepts CLI arguments via
verify-market-capsubcommand or Python function calls - Results show color-coded deviation percentages with a 5% hard failure threshold
- The tool integrates automatically with Claude Code skills for pre-publication quality checks
Frequently Asked Questions
What deviation threshold triggers a failure in financial_rigor.py?
The validation fails when the absolute deviation between calculated and reported market cap exceeds 5%. Deviations between 1% and 5% generate warnings but pass validation, while deviations under 1% pass cleanly.
Why does financial_rigor.py use Decimal instead of float?
The module implements an Exact Decimal Engine (_CTX context and exact() helper at lines 24-38) to avoid floating-point drift errors common in IEEE 754 arithmetic. This ensures mathematically exact calculations when multiplying price by shares and comparing against reported values.
Can I validate market caps in currencies other than USD?
Yes. The --currency CLI argument and currency Python parameter accept any currency code (e.g., HKD, CNY, EUR). The fmt_number() function (lines 40-55) automatically formats output using appropriate units (亿, 万亿 for Asian markets; B, T for Western).
How do I integrate this into automated research pipelines?
The script is designed for automatic invocation by Claude Code skills as documented in AGENTS.md. You can also import financial_rigor as a module in Python scripts or shell out to the CLI in bash workflows. The function returns a Boolean and exit codes (0 for pass, 1 for fail) suitable for CI/CD gates.
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 →