Metadata-Version: 2.4
Name: fin123-core
Version: 0.7.4
Summary: Polars-backed financial workbook engine with local browser UI
Author: fin123 contributors
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.11
Requires-Dist: click>=8.0
Requires-Dist: fastapi>=0.100
Requires-Dist: lark>=1.1
Requires-Dist: polars>=1.0
Requires-Dist: python-multipart>=0.0.6
Requires-Dist: pyyaml>=6.0
Requires-Dist: uvicorn>=0.20
Provides-Extra: dev
Requires-Dist: httpx>=0.24; extra == 'dev'
Requires-Dist: openpyxl>=3.1; extra == 'dev'
Requires-Dist: pytest-tmp-files>=0.0.2; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Provides-Extra: xlsx
Requires-Dist: openpyxl>=3.1; extra == 'xlsx'
Description-Content-Type: text/markdown

# fin123-core

Deterministic financial modeling engine.
Spreadsheet models that behave like software.

fin123-core is the standalone, open-source core of the fin123 platform.
It runs entirely on your machine -- no database, no server, no account required.

## What's New in 0.6.0

- **Research Working Memory** -- explore model assumptions freely. Every parameter state is remembered. Branch, bookmark, compare, and return to prior work. History panel and graph view in the side panel.
- **Surface Mode** -- explore a model as a 2D heatmap. Two axis variables, live cursor interaction, secondary knobs that deform the surface in real time. Every point is a real model evaluation. Capture points into research memory.
- **Terminal Mode** -- operate models as programs. `commit` is the primary execution action.
- **Scenarios** -- label committed runs, load them back, compare side-by-side.
- **Sweeps** -- run a model across one parameter. Each row is a real execution with a run_id.
- **Grids** -- run a model across two parameters. Matrix output in terminal.
- **AI Workbench** -- generate add-ins as governed code artifacts. Draft, validate, apply, commit.
- **Plugin Manager** -- applied add-ins load into runtime during builds.
- **Four Modes** -- Spreadsheet (author), System (inspect), Terminal (operate), Surface (explore).

## Core Concepts

**commit** -- persist current model state and execute a deterministic build. Produces a run_id, scalar outputs, and table outputs. Identical inputs always produce identical outputs.

**scenario** -- a named label over a committed run. Captures inputs, outputs, and the run_id that produced them. Not a substitute for commit; a label over reality.

**sweep** -- run the same model multiple times while varying one parameter. Each row is a real execution with its own run_id and outputs. Not a recalculated cell.

**grid** -- run the same model across two parameters simultaneously. Produces a matrix of one output scalar. Each cell is a real execution.

**draft** -- a code artifact generated by AI or written manually. Must be validated and applied explicitly before it participates in builds. Immutable once created; revisions create new drafts.

**plugin** -- a Python file in `plugins/` that registers scalar or table functions via `@register_scalar` / `@register_table`. Applied drafts become plugins. Plugins are loaded, validated, and hashed during every build.

**research memory** -- working memory for model exploration. Every parameter state you visit is kept as a frame. Branch to explore alternatives. Bookmark states as waypoints. Attach notes as observations. Return to any prior state without rebuilding. No snapshots or runs created -- separate from the canonical lifecycle.

## Modes

fin123 presents the same workbook through four modes:

| Mode | Purpose | Primary surface |
|------|---------|----------------|
| Spreadsheet | Author models | Grid, formula bar |
| System | Inspect runtime state | Grid + side panel (scalars, builds, checks) |
| Terminal | Operate models | Command shell with structured output |
| Surface | Explore model space | 2D heatmap with live cursor and knobs |

Same workbook. Same runtime. Same source of truth. Modes change presentation, not state.

## What is Surface Mode?

Surface Mode transforms a spreadsheet model into a 2D heatmap. Pick two input assumptions as axes, pick an output metric, and see the entire model landscape at once.

- **Axes:** Revenue Growth x EBIT Margin (or any two parameters)
- **Primary metric:** Price Target -- displayed large, updates continuously with cursor movement
- **Secondary knobs:** WACC, Terminal Growth -- drag to deform the entire surface in real time
- **Every point on the surface is a real model evaluation** -- not a chart, not an approximation

Surface Mode is an ephemeral exploration layer. No commits, no builds, no runs created. Move the cursor, adjust knobs, see the model respond instantly. The spreadsheet and the surface show the same model -- just different representations.

## What is a Sweep?

A sweep runs the same model multiple times while varying one parameter, producing a table of results.

```
sweep revenue_growth 0.04 0.06 0.08 0.10
```

Each row is a real execution with a run_id, not a recalculated cell. Results are persisted and exportable.

This replaces Excel's Data Table feature with deterministic, auditable execution. Every sweep point is a committed build that can be independently verified.

Grids extend this to two parameters:

```
grid revenue_growth 0.04 0.06 0.08 vs wacc 0.08 0.09 0.10 --output value_per_share
```

## Research Working Memory

Research memory tracks what you explored without creating snapshots or builds. Change an assumption, try another, go back -- the system remembers every state.

```
# Explore freely
set revenue_growth = 0.08
set revenue_growth = 0.12
back                            # return to revenue_growth = 0.08

# Bookmark important states
waypoint base_case
observe "margin looks tight at 8%"

# Branch to explore alternatives
branch bear_case
set revenue_growth = 0.04
set ebit_margin = 0.15

# Compare any two states
rdiff base_case current

# Promote a waypoint to a saved scenario
promote base_case
```

The Research History panel (System mode, side panel) shows all branches and states. Toggle between list and graph views. Click any state to restore it.

Research state lives under `.fin123/research/` in the project directory. It is completely separate from the canonical commit/build lifecycle.

## Example Workflow

Using the benchmark DCF template with AAPL operating data:

```bash
# Create project from template
fin123 init my_dcf --template benchmark_dcf
fin123 ui my_dcf
```

Then in Terminal Mode:

```
# Set assumptions and commit the base case
set active_ticker = AAPL
set revenue_growth = 0.08
set ebit_margin = 0.22
set wacc = 0.10
waypoint base_assumptions
commit
scenario save base

# Change assumptions for bull case
set revenue_growth = 0.14
set ebit_margin = 0.28
set wacc = 0.08
commit
scenario save bull

# Compare base vs bull
compare base bull

# Sweep revenue growth across 5 values
sweep revenue_growth 0.04 0.06 0.08 0.10 0.12 --outputs value_per_share enterprise_value implied_upside

# 2D sensitivity grid: revenue growth vs WACC
grid revenue_growth 0.04 0.08 0.12 vs wacc 0.08 0.10 0.12 --output value_per_share

# Generate an AI add-in
ai draft addin "calculate compound annual growth rate from start and end values over n periods"
validate draft draft_0001
apply draft draft_0001
commit
```

## Runnable Demo

A complete end-to-end demo is included in `demo/`.

```bash
# Automated CLI demo (commit, compare, sweep, grid)
bash demo/run_demo.sh

# Interactive Terminal Mode demo
fin123 init demo_dcf --template benchmark_dcf
fin123 ui demo_dcf
# Switch to Terminal Mode, run commands from demo/terminal_commands.txt
```

The demo runs a 66,000-row AAPL DCF valuation through:
- Base case and bull case commits
- Scenario comparison (value_per_share: 1,402.63 -> 2,692.01)
- 5-point revenue growth sweep
- 3x3 sensitivity grid (revenue growth vs WACC)
- AI add-in generation (requires `ANTHROPIC_API_KEY`)

See `demo/README.md` for full instructions and talking points.

## What You Get

- **Workbook engine** -- Polars-backed scalar DAG + table LazyFrame evaluation.
- **Formula language** -- Lark LALR(1) parser with Excel-like syntax (`=SUM(revenue * (1 - tax_rate))`).
- **Local browser UI** -- FastAPI on localhost, canvas-based spreadsheet grid, keyboard-first.
- **Deterministic lifecycle** -- Edit -> Commit -> Build -> Verify. Identical inputs always produce identical outputs.
- **Terminal runner** -- `commit`, `scenario`, `sweep`, `grid`, `compare` in a structured terminal shell.
- **Surface Mode** -- 2D heatmap exploration with live cursor, bilinear interpolation, and secondary knobs.
- **Research memory** -- reversible exploration with branching, waypoints, observations, history panel, and graph view.
- **AI Workbench** -- generate, revise, validate, and apply add-in code artifacts.
- **Plugin system** -- applied add-ins loaded and validated during builds.
- **Versioning** -- immutable snapshots, builds, and artifacts with SHA-256 integrity.
- **XLSX import** -- best-effort import of Excel workbooks with formula classification.
- **Templates** -- pre-built starting points for common financial model patterns.
- **Offline-first** -- `fin123 build` reads only local files. Zero network calls.
- **Worksheet runtime** -- deterministic projections of build output tables with derived columns, sorts, flags, and compiled artifacts.
- **Doctor** -- deterministic preflight validation (`fin123 doctor`).

## Quick Start

### Install from source (editable / development mode):

```bash
git clone https://github.com/reckoning-machines/fin123-core.git
cd fin123-core
pip install -e ".[dev]"
```

> **End-user binaries** (no Python required) are available on
> [GitHub Releases](https://github.com/reckoning-machines/fin123-core/releases)
> for macOS (arm64) and Windows (x86_64).

### Usage

```bash
# Create a project from the benchmark DCF template
fin123 init my_model --template benchmark_dcf

# Launch the browser UI
fin123 ui my_model

# Build (evaluate the workbook)
fin123 build my_model

# Commit the workbook snapshot
fin123 commit my_model

# Verify build integrity
fin123 verify 20260227T120000_run_1 --project my_model

# Preflight checks
fin123 doctor
```

## Browser UI

```bash
fin123 ui my_model
```

Opens a local spreadsheet editor at `http://localhost:<port>` with:

- Canvas grid with sparse rendering and keyboard-first navigation.
- Mode switcher: Spreadsheet / System / Terminal / Surface.
- Terminal shell with deterministic runner commands.
- Formula bar with live validation.
- Multi-sheet tabs, copy/paste (TSV), font color formatting.
- Commit (Ctrl+S), Build (Ctrl+Enter), dependency highlight (Ctrl+P).
- XLSX import via Ctrl+O or `fin123 import-xlsx model.xlsx my_model`.
- Version browsing -- select any historical snapshot (read-only).

## CLI Commands

The CLI executable is `fin123` in both core and pod.

### Core lifecycle

| Command | Description |
|---------|-------------|
| `fin123 init <dir>` | Scaffold a new project (optionally from template) |
| `fin123 commit <dir>` | Snapshot current workbook |
| `fin123 build <dir>` | Build workbook (evaluate graphs, persist outputs) |
| `fin123 verify <run_id> --project <dir>` | Verify a build's integrity |
| `fin123 diff run <a> <b>` | Compare two builds |
| `fin123 diff version <v1> <v2>` | Compare two workbook versions |
| `fin123 export <dir>` | Export latest build outputs |
| `fin123 doctor` | Preflight and compliance validation |

### Additional commands

| Command | Description |
|---------|-------------|
| `fin123 batch build <dir>` | Run batch builds from a params CSV |
| `fin123 artifact list <dir>` | List versioned artifacts |
| `fin123 gc <dir>` | Garbage collect old builds and artifacts |
| `fin123 import-xlsx <file> <dir>` | Import an Excel workbook |
| `fin123 template list` | List available templates |
| `fin123 events <dir>` | Show structured event log |
| `fin123 ui <dir>` | Launch the browser UI |
| `fin123 worksheet compile <spec>` | Compile a worksheet from spec + build table |
| `fin123 demo <name>` | Run a built-in demo |

### Global flags

Global flags must precede the subcommand: `fin123 --json build my_model`.

| Flag | Description |
|------|-------------|
| `--json` | Machine-readable JSON output |
| `--quiet` | Suppress non-essential output |
| `--verbose` | Verbose diagnostic output |

### Exit codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Generic error |
| 2 | Invalid usage / bad arguments |
| 3 | Verification failure (hash mismatch, non-determinism) |
| 4 | Enterprise-only feature (core) |
| 5 | Dependency / environment missing |

### JSON output contract

Every command with `--json` prints exactly one JSON object to stdout:

```json
{
  "ok": true,
  "cmd": "doctor",
  "version": "0.5.0",
  "data": { ... },
  "error": null
}
```

## AI Workbench (0.5.0)

AI generates add-ins as reviewable code artifacts. Drafts must be validated and applied explicitly.

**Implemented:**
- `ai draft addin` -- generate a plugin from natural language
- `ai revise draft` -- iterate on a draft without mutating the original
- `ai explain formula / output` -- non-mutating explanations with truncation
- `draft lineage` -- view the revision chain
- `validate draft` -- policy scan (syntax, imports, eval/exec, network, metadata)
- `apply draft` -- copy validated code to `plugins/`
- Plugin manager -- loads applied plugins during builds

**Not implemented (by design):**
- Branching revision trees
- Silent mutation of workbook state
- Automatic apply or commit
- Conversational AI

The system is intentionally linear and explicit. Drafts are immutable artifacts; revisions create new drafts.

## Demos

```bash
fin123 demo ai-governance        # AI plugin governance + compliance
fin123 demo deterministic-build  # Deterministic build verification
fin123 demo batch-sweep          # Batch parameter sweep scenarios
fin123 demo data-guardrails      # Data quality enforcement
```

No external data or configuration required.

## Project Layout

```
my_model/
  workbook.yaml       # Workbook specification (sheets, params, tables, outputs)
  fin123.yaml         # Project config (GC limits, mode)
  inputs/             # Source data (CSV, Parquet)
  plugins/            # Applied add-in plugins
  runs/               # Immutable build records
  artifacts/          # Versioned workflow artifacts
  snapshots/          # Workbook spec history (v0001, v0002, ...)
  .fin123/            # Terminal state (scenarios, sweeps, grids, drafts)
  .fin123/research/   # Research working memory (sessions, branches, frames)
  cache/              # Ephemeral hash cache
```

## Documentation

- [ARCHITECTURE.md](ARCHITECTURE.md) -- core architecture.
- [docs/concepts.md](docs/concepts.md) -- core concepts: commit, scenario, sweep, grid, draft.
- [docs/terminal.md](docs/terminal.md) -- Terminal Mode command reference.
- [docs/CLI_SPEC.md](docs/CLI_SPEC.md) -- CLI specification.
- [docs/worksheets.md](docs/worksheets.md) -- worksheet runtime.
- [docs/formulas_and_views.md](docs/formulas_and_views.md) -- formula semantics.
- [docs/RUNBOOK.md](docs/RUNBOOK.md) -- operational runbook.
- [CHANGELOG.md](CHANGELOG.md) -- release notes.

Built by Reckoning Machines

## License

Apache-2.0 -- see [LICENSE](LICENSE).
