Best Practices for Using AI Berkshire's Financial Rigor Tools
AI Berkshire's Financial Rigor Toolkit eliminates floating-point drift in financial analysis by enforcing exact decimal arithmetic and automated validation checks across market-cap verification, valuation metrics, and cross-source data consistency.
The xbtlin/ai-berkshire repository ships a self-contained validation suite in tools/financial_rigor.py designed for integration with Claude-Code skills. This zero-dependency toolkit ensures deterministic calculations when small rounding errors could flip critical investment ratios across decision thresholds.
Exact Decimal Arithmetic as the Foundation
The toolkit avoids floating-point errors by implementing a custom decimal context that guarantees reproducible results across all financial calculations.
The _CTX Precision Engine
At lines 28-38 of tools/financial_rigor.py, the module defines a global decimal context _CTX with 28-digit precision and ROUND_HALF_EVEN rounding. The exact() function converts all inputs to Decimal objects via string conversion before calculation, preventing IEEE 754 floating-point representation errors. This implementation ensures that price-to-earnings ratios, market-cap calculations, and valuation multiples remain deterministic regardless of execution environment.
Human-Readable Formatting with fmt_number()
The fmt_number() function converts large Decimal values into "亿/万亿/B/T" units while preserving the raw decimal for downstream calculations. Always pair formatted output with the underlying Decimal values to prevent unit-mixup errors when presenting results to stakeholders.
Core Validation Functions
The toolkit provides specialized verification functions that enforce data integrity through automated tolerance checks and consensus building.
Market-Cap Verification (verify_market_cap())
Implemented at lines 61-71, this function computes price × shares and compares it against reported market caps. The validation flags deviations greater than 5% as errors and greater than 1% as warnings.
Best practices for invocation:
- Pass consistent currency units to the
--currencyargument - Verify
--sharesreflects the latest filing including stock splits and buy-backs - Inspect printed deviation percentages; gaps exceeding 5% indicate data-consistency problems requiring investigation
python3 tools/financial_rigor.py verify-market-cap \
--price 510 \
--shares 9.11e9 \
--reported 4.65e12 \
--currency HKD
Valuation Metrics Verification (verify_valuation())
This function calculates PE, PB, ROE, P/FCF, dividend yield, and PS ratios from raw inputs, storing results in a dictionary for downstream use. At lines 58-61, the function prints a "✅ 以上指标均使用精确十进制计算" confirmation to verify exact decimal usage.
Input guidelines:
- Provide all optional arguments with reliable data; missing values are omitted automatically
- Maintain consistent currency units between
priceand per-share figures - Review the printed metric labels to ensure proper mapping of financial inputs
python3 tools/financial_rigor.py verify-valuation \
--price 510 \
--eps 23.5 \
--bvps 120 \
--fcf-per-share 18 \
--dividend 2.4
Cross-Source Data Validation (cross_validate())
Located at lines 66-71, this function accepts a JSON mapping of {source: value} pairs, constructs a median reference, and flags outliers beyond the default 2% tolerance.
Validation workflow:
- Feed primary sources first (company filings, exchange data)
- Investigate sources deviating >2% from the median consensus
- Apply weighting schemes when specific sources demonstrate systematic bias
- Reference the printed consensus value for final reporting
python3 tools/financial_rigor.py cross-validate \
--field revenue \
--values '{"年报": 7518, "Yahoo": 7500, "StockAnalysis": 7520}' \
--unit 亿
Advanced Screening and Projection Tools
Beyond basic verification, the toolkit provides specialized functions for fraud detection and scenario modeling.
Benford-Law Screening (benford_check())
This statistical test analyzes leading-digit distributions to detect anomalies in financial datasets. At lines 30-34, the implementation warns if fewer than 50 data points are provided, as small samples produce statistically unreliable results.
Implementation standards:
- Supply at least 50 financial figures (e.g., revenue line items or transaction amounts)
- Treat non-conforming results as red flags requiring investigation rather than definitive fraud proof
- Use the function as a preliminary screen before deep forensic analysis
python3 tools/financial_rigor.py benford \
--values '[1234, 2345, 3456, 4567, 5678, 6789, 7890, 8910, …]'
Exact Calculator (exact_calc())
The calculator safely evaluates arithmetic expressions using the decimal context defined at lines 98-102. The parser strictly validates input characters, aborting evaluation if non-arithmetic characters (anything other than +,-,*,/,(),.eE) are detected.
Security constraints:
- Use scientific notation (
e9,e12) for large numbers to avoid typing errors - Validate expressions before submission; the function returns precise
Decimalresults or aborts on invalid input
python3 tools/financial_rigor.py calc \
--expr '510 * 9.11e9'
Three-Scenario Valuation (three_scenario_valuation())
This function projects target prices under optimistic, neutral, and pessimistic growth assumptions. Lines 43-57 format output as a comparison table highlighting percentage changes and implausible jumps between scenarios.
Parameter requirements:
- Express growth rates as annual decimals (0.15 = 15%)
- Maintain consistent
--yearsacross all scenarios to prevent mismatched time horizons - Format
--sharesin billions (亿 units) as expected by the tool
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 Claude-Code Skills
The toolkit is architected for automated invocation through Claude-Code skills defined in skills/*.md files, particularly skills/quality-screen.md.
Automation guidelines:
- Restrict manual CLI usage to debugging scenarios; production workflows should trigger through skill definitions
- Capture printed output (delimited by
=*60 headers) for audit trails - Respect boolean return flags from verification functions; downstream skills should abort workflows when
verify_market_cap()orverify_valuation()returnsFalse - Maintain updated data files (
data/fundamentals.json,data/morningstar_fair_value_*.csv) to reflect latest filings before automated checks
Summary
- Exact decimal arithmetic via
_CTXandexact()prevents floating-point drift in all financial calculations - Market-cap verification requires consistent currency units and current share counts, flagging >5% deviations as critical errors
- Cross-source validation uses median consensus with 2% tolerance to identify data outliers across multiple financial databases
- Benford-Law screening demands minimum 50 data points for statistical validity and serves as a fraud detection red flag
- Zero-dependency design ensures deterministic installs across environments using only Python standard library components
Frequently Asked Questions
How does the Exact Decimal Engine prevent rounding errors in financial ratios?
The engine defined at lines 28-38 uses decimal.Decimal with 28-digit precision and ROUND_HALF_EVEN rounding via the _CTX context. By converting floats to strings before Decimal instantiation, the exact() function eliminates IEEE 754 floating-point representation errors that could otherwise flip PE or P/FCF ratios across critical investment thresholds.
What is the minimum sample size required for Benford-Law screening?
The benford_check() function requires at least 50 numeric values to produce statistically meaningful results. At lines 30-34, the implementation explicitly warns when sample sizes are insufficient, as smaller datasets generate high variance in leading-digit frequency distributions that limit the test's reliability for fraud detection.
How should I format share counts for the Three-Scenario Valuation tool?
The --shares argument expects values in billions (亿 units). When calling three_scenario_valuation(), convert raw share counts to this scale (e.g., 9.11 billion shares becomes --shares 9.11) and ensure growth rates are provided as annual decimals (e.g., 0.15 for 15% growth) rather than percentages.
Why does the Financial Rigor Toolkit enforce zero external dependencies?
As documented in the top-level docstring at lines 7-9, the script uses only Python standard library modules to ensure deterministic installations across development, staging, and production environments. This design eliminates dependency version conflicts and guarantees that decimal arithmetic behavior remains consistent regardless of the deployment context.
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 →