How to Configure decimal.Decimal for Financial Calculations in AI-Berkshire

AI-Berkshire configures a global decimal.Context with 28-digit precision and the ROUND_HALF_EVEN rounding rule, then wraps all numeric inputs with an exact() helper to eliminate floating-point drift in monetary calculations.

The AI-Berkshire repository relies exclusively on Python's standard-library decimal module to handle monetary values, share counts, and valuation ratios. By centralizing the Decimal configuration in tools/financial_rigor.py, the codebase ensures deterministic financial calculations free from binary floating-point artifacts. This approach guarantees that market-cap verifications and cross-source validations remain accurate to the exact decimal place.

Setting Up the Global Decimal Context

The foundation of AI-Berkshire's numerical precision lies in a centralized Context configuration that governs all financial arithmetic.

Creating the Shared Context

In tools/financial_rigor.py at line 28, the repository defines a global context named _CTX:


# tools/financial_rigor.py (line 28)

from decimal import Context, ROUND_HALF_EVEN

_CTX = Context(prec=28, rounding=ROUND_HALF_EVEN)

This configuration sets precision to 28 digits and uses round-half-even (banker's rounding), the industry standard for financial calculations. All subsequent arithmetic operations reference this shared context to maintain consistency across the codebase.

The exact() Input Wrapper

Raw floating-point numbers introduce binary representation errors when converted directly to Decimal. The exact() function at lines 31-38 solves this by converting inputs through string representation:


# tools/financial_rigor.py (lines 31-38)

def exact(value):
    """Convert any numeric to Decimal without binary float errors."""
    if isinstance(value, Decimal):
        return value
    return Decimal(str(value))

This approach prevents scenarios where Decimal(510.0) produces 510.00000000000006..., ensuring exact decimal representation regardless of whether the input is a string, integer, or float.

Performing Financial Calculations with Decimal

With the context configured, AI-Berkshire performs critical financial operations using the shared infrastructure to prevent floating-point artifacts.

Market Capitalization Verification

The repository validates reported market caps against calculated values using precise multiplication. In tools/financial_rigor.py at line 67, the code multiplies price by shares using the global context:

from tools.financial_rigor import exact, _CTX

price = exact(510)              # → Decimal('510')

shares = exact('9.11e9')        # → Decimal('9.11e9')

reported = exact('4.65e12')     # → Decimal('4.65e12')

calc = _CTX.multiply(price, shares)    # Precise multiplication

deviation = abs(calc - reported) / reported * 100
print(f"Deviation = {deviation:.2f}%")

This pattern ensures that price × shares calculations match reported totals within tight tolerances, catching discrepancies that floating-point math would obscure.

Valuation Ratio Computations

Price-to-earnings and other ratios require deterministic division without intermediate rounding errors:

from tools.financial_rigor import exact, _CTX

price = exact(510)
eps = exact(23.5)

pe = _CTX.divide(price, eps)    # → Decimal with 28-digit precision

print(f"PE = {pe:.2f}x")

Using _CTX.divide() guarantees that PE, PB, ROE, and FCF yield calculations maintain exact precision through intermediate steps.

Integrating Decimal Across the Codebase

The Decimal configuration extends beyond the core module through consistent imports and helper functions.

Cross-Module Usage

Additional tools import the same Decimal objects to ensure consistency throughout the analysis pipeline:

  • tools/report_audit.py (line 30): Imports the configuration for audit-time verification of extracted report figures
  • tools/ashare_data.py (line 21): Converts raw market data strings to Decimal objects using the same methodology

# Example from ashare_data.py workflow

from decimal import Decimal

price_str = "510.00"
price = Decimal(price_str)           # Safe string conversion

market_cap = Decimal("4.65e12")        # Exact scientific notation

Formatting Large Numbers

The fmt_number() function at lines 40-54 handles output formatting, respecting Chinese units (亿, 万亿) and scientific notation while maintaining the underlying Decimal precision:


# tools/financial_rigor.py (lines 40-54)

def fmt_number(value):
    """Format respecting Chinese units and scientific notation."""
    # Implementation handles 亿/万亿 units and scientific notation formatting

    pass

Customizing Precision for Specific Analyses

While the default 28-digit precision suits most financial applications, specific analyses may require adjustment. Modify the global context definition in tools/financial_rigor.py:


# Example: 34-digit precision for ultra-large market caps

_CTX = Context(prec=34, rounding=ROUND_HALF_EVEN)

All helper functions (exact, fmt_number, and verification utilities) automatically respect the updated _CTX without requiring changes elsewhere in the codebase.

Summary

  • AI-Berkshire configures a global decimal.Context with 28-digit precision and round-half-even rounding in tools/financial_rigor.py (line 28).
  • The exact() helper function (lines 31-38) converts all numeric inputs to Decimal via string representation, preventing floating-point inheritance errors.
  • Use _CTX.multiply() and _CTX.divide() for arithmetic operations to maintain precision in market-cap verification and valuation ratios.
  • Cross-module consistency is achieved by importing the same Decimal configuration in report_audit.py and ashare_data.py.
  • Precision is customizable by updating the _CTX definition, with all dependent functions automatically respecting the new configuration.

Frequently Asked Questions

Why does AI-Berkshire use Decimal instead of float for financial calculations?

Binary floating-point cannot represent decimal fractions exactly, leading to rounding errors that accumulate in complex financial models. AI-Berkshire uses Python's decimal.Decimal with a custom Context to ensure that monetary values, share counts, and ratios remain exact through multiple calculation steps, preventing subtle drifts that could trigger false alerts in cross-source validation.

How does the exact() function prevent floating-point errors?

The exact() function in tools/financial_rigor.py converts inputs to strings before creating Decimal objects. When you pass a float like 510.0 directly to Decimal(), Python incorporates the binary approximation (510.00000000000006...). By using Decimal(str(value)), exact() captures the intended decimal representation, eliminating inherited binary errors from CSV imports or API responses.

Can I change the decimal precision for a single calculation without affecting the global context?

While the global _CTX provides consistency, you can create local contexts for specific calculations. However, AI-Berkshire's architecture encourages modifying the global _CTX definition in tools/financial_rigor.py if your analysis consistently requires different precision (such as 34 digits for ultra-large market caps), ensuring all helper functions and verification utilities use the same standard.

Where is the Decimal configuration used outside of financial_rigor.py?

The same Decimal configuration appears in tools/report_audit.py (line 30) for auditing extracted financial reports and in tools/ashare_data.py (line 21) for parsing raw A-share market data. Both modules import the _CTX and exact() functionality to maintain consistency with the core financial rigor standards.

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 →