# How to Customize the Financial Rigor Tools in AI Berkshire

> Customize AI Berkshire financial rigor tools by adding new metrics to the CLI framework. Learn how to register custom functions and maintain decimal precision for accurate financial validation.

- Repository: [Xbt Lin/ai-berkshire](https://github.com/xbtlin/ai-berkshire)
- Tags: how-to-guide
- Published: 2026-06-28

---

**The AI Berkshire financial rigor toolkit provides a modular CLI framework in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) that allows you to add custom validation metrics by creating new helper functions, registering them with argparse sub-parsers, and wiring them into the command dispatcher—while maintaining exact decimal precision throughout all calculations.**

The AI Berkshire repository provides a robust financial analysis environment powered by the Financial Rigor Toolkit. Located in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py), this module serves as the core engine for data-validation checks used throughout the system. Understanding how to customize the financial rigor tools in AI Berkshire enables you to extend its exact-decimal arithmetic capabilities with domain-specific metrics and validation rules.

## Architecture of the Financial Rigor Toolkit

The toolkit implements a clean separation between the CLI interface, the exact decimal calculation engine, and individual validation routines.

### The Exact Decimal Engine

At the heart of the system lies a shared `Context` object (`_CTX`) defined at lines 28-31 of [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py), configured with 28-digit precision to eliminate floating-point drift. All numeric inputs pass through the `exact()` function (lines 31-38) before calculation, ensuring every financial operation maintains decimal integrity.

### Command Structure and Dispatch

The `main()` function (lines 67-86) uses `argparse.ArgumentParser` with sub-parsers to handle commands like `verify-market-cap`, `verify-valuation`, `cross-validate`, `benford`, `calc`, and `three-scenario`. Each sub-command maps to a specific helper function—such as `verify_market_cap`, `verify_valuation`, or `cross_validate`—that follows a consistent pattern: convert inputs with `exact()`, perform calculations using `_CTX`, print formatted output via `fmt_number`, and return structured results as dictionaries.

## Adding Custom Validation Logic

To implement a new financial check, create a helper function following the established architectural pattern used by existing validators.

### Step 1: Create the Helper Function

Place your function in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) alongside existing helpers. The function must accept raw inputs, convert them using `exact()`, perform exact arithmetic via the `_CTX` object, print a formatted report, and return a dictionary.

For example, to add a liquidity ratio check:

```python
def liquidity_ratio(current_assets, current_liabilities):
    """Calculate and validate the current ratio (资产/负债)."""
    ca = exact(current_assets)
    cl = exact(current_liabilities)
    ratio = _CTX.divide(ca, cl)
    print("=" * 60)
    print("流动比率 (Liquidity Ratio)")
    print("=" * 60)
    print(f"  流动资产: {fmt_number(ca)}")
    print(f"  流动负债: {fmt_number(cl)}")
    print(f"  当前比率: {ratio:.2f}")
    return {"liquidity_ratio": float(ratio)}

```

### Step 2: Register the CLI Command

In the `main()` function around line 80, add a new sub-parser using `sub.add_parser()`. Define your arguments with appropriate types and help text:

```python
liq = sub.add_parser("liquidity", help="计算流动比率")
liq.add_argument("--assets", type=float, required=True, help="流动资产")
liq.add_argument("--liabilities", type=float, required=True, help="流动负债")

```

### Step 3: Wire the Dispatcher

Extend the `if/elif` chain in the dispatcher (typically around lines 27-48) to route your new command to its helper function:

```python
elif args.command == "liquidity":
    liquidity_ratio(args.assets, args.liabilities)

```

**Usage:**

```bash
python3 tools/financial_rigor.py liquidity --assets 3.2e9 --liabilities 1.1e9

```

## Customizing Existing Validation Behavior

Beyond adding new commands, you can modify hard-coded thresholds and output formats to suit your requirements.

### Configurable Tolerance Levels

Many checks use hard-coded percentage thresholds, such as the `deviation > 5` check in `verify_market_cap` (lines 80-86). Refactor these to accept parameters through the function signature and expose them as CLI flags:

```python
def verify_market_cap(price, shares, reported_cap, currency="", tolerance=5.0):
    # ... calculation logic ...

    if deviation > tolerance:
        # ... alert logic ...

```

Then add the corresponding argument to the sub-parser:

```python
mc.add_argument("--tolerance", type=float, default=5.0,
                help="容差百分比 (default 5.0)")

```

Now users can run:

```bash
python3 tools/financial_rigor.py verify-market-cap \
    --price 510 --shares 9.11e9 --reported 4.65e12 \
    --currency HKD --tolerance 3

```

### Output Formatting and Localization

The `fmt_number` function (lines 40-54) controls unit conversion and display formatting, automatically selecting appropriate units (万, 亿, B, T…). Modify this function to support additional units (such as "千") or replace the `print` statements in helpers with structured JSON output or Python logging for downstream automation.

## Integrating with AI Berkshire Skills

When you add a new command to the toolkit, the AI agents require updated skill definitions to discover and invoke it.

The toolkit integrates automatically with Claude Code skills as documented in [`AGENTS.md`](https://github.com/xbtlin/ai-berkshire/blob/main/AGENTS.md). After modifying [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) or adding commands, synchronize the skill definitions by running:

```bash
python3 scripts/sync-codex-skills.py

```

This script regenerates the Codex-style skill definitions under `codex-skills/` and ensures that skills in `skills/` (such as [`skills/valuation/valuation.md`](https://github.com/xbtlin/ai-berkshire/blob/main/skills/valuation/valuation.md)) reflect your new command structure.

## Summary

- The **Financial Rigor Toolkit** resides in [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py) and uses a 28-digit precision decimal engine (`_CTX`) to prevent floating-point errors.
- New validation commands require three steps: creating a helper function that uses `exact()` for input conversion, registering a sub-parser in `main()`, and adding a dispatch case to the `if/elif` chain.
- Modify hard-coded thresholds like the 5% deviation limit in `verify_market_cap` or adjust `fmt_number` (lines 40-54) to customize output formatting and units.
- Run `python3 scripts/sync-codex-skills.py` after changes to ensure AI agents can access new commands through the skills system documented in [`AGENTS.md`](https://github.com/xbtlin/ai-berkshire/blob/main/AGENTS.md).

## Frequently Asked Questions

### How do I ensure my custom calculations avoid floating-point errors?

Always wrap numeric inputs with the `exact()` function and perform arithmetic using the `_CTX` object (e.g., `_CTX.multiply(a, b)` or `_CTX.divide(ca, cl)`). This leverages the 28-digit precision `decimal.Context` defined at lines 28-31 of [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py), ensuring all financial calculations maintain exact decimal representation.

### Can I add optional parameters to existing commands like `verify-market-cap`?

Yes. Modify the function signature to accept optional parameters (e.g., `tolerance=5.0`), then add corresponding arguments to the sub-parser in `main()` using `add_argument("--tolerance", type=float, default=5.0)`. Update the dispatcher call to pass `args.tolerance` to the function, allowing users to override defaults like the standard 5% deviation threshold.

### Where do I place new helper functions in the file?

Place new helper functions in the same section as existing ones like `verify_market_cap` and `verify_valuation`, typically between the utility functions and the `main()` function. Maintain the pattern of converting inputs with `exact()`, printing formatted headers with `fmt_number`, and returning result dictionaries for programmatic use.

### How do I make my new command available to the AI agents?

After adding your command to [`tools/financial_rigor.py`](https://github.com/xbtlin/ai-berkshire/blob/main/tools/financial_rigor.py), update the relevant skill documentation in `skills/` and run `python3 scripts/sync-codex-skills.py`. This synchronizes the skill definitions so Claude Code can discover and invoke your new validation routine according to the integration patterns described in [`AGENTS.md`](https://github.com/xbtlin/ai-berkshire/blob/main/AGENTS.md).