How AI Berkshire Ensures Exact Decimal Arithmetic
AI Berkshire eliminates floating-point errors by enforcing a strict conversion pipeline that transforms all numeric inputs into Python Decimal objects via string parsing, ensuring precise financial calculations without binary floating-point drift.
AI Berkshire is an open-source financial analysis toolkit designed for rigorous investment research. The repository implements a specialized exact decimal arithmetic engine to avoid the rounding errors inherent in standard floating-point operations. By centralizing decimal handling in tools/financial_rigor.py, the codebase guarantees that every valuation, ratio, and market-cap computation maintains exact precision.
The Floating-Point Problem in Financial Software
Standard Python float objects use binary64 representation, which cannot exactly represent common decimal values like 0.1. This introduces microscopic errors that compound across complex financial models, leading to incorrect P/E ratios or inaccurate market-cap valuations. AI Berkshire solves this by mandating the decimal module for all monetary calculations and providing a centralized conversion utility.
The Exact Decimal Engine Architecture
The engine consists of three layers: a customized global context, a conversion wrapper that avoids float contamination, and formatting utilities that respect precision settings.
High-Precision Context Configuration
The repository configures a global Decimal context with 28 digits of precision and ROUND_HALF_EVEN rounding mode in tools/financial_rigor.py. This context applies to all subsequent Decimal operations, ensuring consistent behavior across the tools/report_audit.py and tools/ashare_data.py modules.
The exact() Conversion Function
The cornerstone of the system is the exact() function, defined in [tools/financial_rigor.py](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py#L31-L37). This function converts any numeric input—whether int, float, or str—to a Decimal by first coercing it to a string.
from decimal import Decimal
def exact(value) -> Decimal:
"""Convert any numeric to exact Decimal, avoiding float traps."""
if isinstance(value, Decimal):
return Decimal(str(value))
return Decimal(str(value))
Converting through str() prevents the binary floating-point artifacts that would occur if a float were passed directly to the Decimal constructor. For example, exact(0.1) produces Decimal('0.1') exactly, rather than Decimal('0.1000000000000000055511151231257827021181583404541015625').
Consistent Formatting with fmt_number()
The same file provides fmt_number() (lines 40-50), which formats Decimal instances for display while respecting the custom context. This ensures that rounded values maintain the engine's precision standards and supports optional unit suffixes like "USD" or "CNY".
Implementation Across the Codebase
The exact decimal arithmetic strategy is not confined to a single utility file. Multiple tools import and rely on these primitives to ensure audit-grade accuracy.
Core Utilities in financial_rigor.py
The primary implementation resides in tools/financial_rigor.py, which exports exact(), fmt_number(), and the pre-configured Context. This serves as the single source of truth for decimal behavior throughout the repository.
Audit-Grade Calculations in report_audit.py
The tools/report_audit.py module utilizes Decimal directly for verification arithmetic (lines 30-36). It imports the same context and rounding constants, ensuring that audit calculations match the precision of the primary data pipeline.
Market Data Processing in ashare_data.py
In tools/ashare_data.py, the exact() function processes raw price and market-capitalization data (lines 21-188). By wrapping incoming numeric strings through exact(), the module prevents floating-point corruption before values enter any calculation chain involving share prices or equity valuations.
Practical Usage Examples
To perform exact calculations in your own scripts using AI Berkshire's engine:
from tools.financial_rigor import exact, fmt_number
# Convert raw inputs to exact Decimals
price = exact(123.45) # Decimal('123.45')
shares = exact('1000') # Decimal('1000')
market_cap = price * shares # Precise multiplication
# Format for reporting
print(fmt_number(market_cap, "USD"))
# Output: "123,450.00 USD"
When processing A-share market data:
from tools.ashare_data import process_ashare
# Internal calls to exact() ensure precision
result = process_ashare(raw_price="57.89", raw_market_cap="2.3e10")
# All downstream calculations remain exact
Summary
- String-based conversion: The
exact()function intools/financial_rigor.pyconverts all inputs toDecimalviastr()to eliminate float binary errors before they enter calculation chains. - Global context: A high-precision context with 28 digits and
ROUND_HALF_EVENrounding ensures consistent, reproducible rounding across all modules. - Centralized utilities:
fmt_number()andexact()provide a single API for all numeric operations, preventing precision drift. - Cross-module consistency:
tools/report_audit.pyandtools/ashare_data.pyinherit the same precision standards, ensuring that audit-grade calculations and market data processing maintain exact decimal arithmetic throughout the analysis pipeline.
Frequently Asked Questions
Why does AI Berkshire convert numbers to strings before creating Decimals?
Passing a Python float directly to Decimal() preserves the float's underlying binary representation, which often includes microscopic base-2 artifacts. By converting to str() first in the exact() function, AI Berkshire ensures the Decimal represents the exact base-10 value intended by the user, not the nearest binary approximation.
What precision level does the AI Berkshire decimal engine use?
The engine configures a global Decimal context with 28 digits of precision and ROUND_HALF_EVEN rounding mode. This exceeds the requirements for standard financial calculations and prevents precision loss during intermediate steps in complex valuation models.
How do I import the exact decimal utilities into my own analysis scripts?
Import the conversion and formatting functions directly from the financial rigor module:
from tools.financial_rigor import exact, fmt_number, Decimal
This grants access to the same precision context and rounding rules used throughout the AI Berkshire codebase, ensuring your calculations remain consistent with the repository's exact decimal arithmetic standards.
Where does AI Berkshire apply exact decimal arithmetic outside of financial_rigor.py?
The exact() function is heavily utilized in tools/ashare_data.py for processing stock prices and market capitalizations, while tools/report_audit.py relies on Decimal for verification arithmetic. Any module performing monetary calculations imports these primitives to maintain exact precision across the entire investment research pipeline.
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 →