Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
name: CI
on: [push, pull_request]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
Expand All @@ -13,8 +15,15 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
- run: pip install -r requirements-dev.txt
- name: Unit tests (Appendix J examples, products, optimizer oracle, workbook portability, skills)
run: python -m pytest -q
- name: Lint (ruff)
run: ruff check src tests scripts
- name: Type check (mypy)
run: mypy src/capkit
- name: Unit tests with coverage
run: |
python -m coverage run --source=src/capkit -m pytest -q
python -m coverage report --fail-under=85
python -m coverage report --include=src/capkit/apr.py,src/capkit/disclosures.py --fail-under=94
- name: Rebuild workbook and verify it against the engine (fuzzed)
run: |
PYTHONPATH=src python -m capkit workbook '{"path": "workbook/CapKit.xlsx"}'
Expand All @@ -23,3 +32,11 @@ jobs:
run: python scripts/build_skills.py --check
- name: Committed workbook is up to date
run: git diff --exit-code --stat workbook/CapKit.cells.json
test-py39:
# the oldest Python the README and pyproject promise; no longer on the hosted runner image
runs-on: ubuntu-latest
container: python:3.9-slim
steps:
- uses: actions/checkout@v4
- run: pip install -r requirements-dev.txt
- run: python -m pytest -q
25 changes: 25 additions & 0 deletions .github/workflows/deep-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: deep property tests

on:
schedule:
- cron: "17 6 * * *"
workflow_dispatch:

permissions:
contents: read

jobs:
deep:
runs-on: ubuntu-latest
timeout-minutes: 60 # measured: 7.8 min for all three files at 2,000 examples (Python 3.9, laptop)
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: pip install -r requirements-dev.txt
- name: Property tests, 2000 examples per property
env:
HYPOTHESIS_PROFILE: deep
PYTHONPATH: src
run: python -m pytest -q tests/test_properties.py tests/test_hardening.py tests/test_api_fuzz.py
23 changes: 19 additions & 4 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,31 @@ jobs:
with:
python-version: "3.12"
- run: pip install -r requirements-dev.txt
- name: Tag matches the package version
run: |
v=$(python -c 'import tomllib;print(tomllib.load(open("pyproject.toml","rb"))["project"]["version"])')
test "${GITHUB_REF_NAME#v}" = "$v" || { echo "tag $GITHUB_REF_NAME != version $v"; exit 1; }
- run: ruff check src tests scripts
- run: mypy src/capkit
- run: python -m pytest -q
- run: python scripts/build_skills.py --check
- run: python scripts/build_skills.py
- name: Publish release with skill archives and workbook
- name: Regenerate and verify the workbook that ships
run: |
PYTHONPATH=src python -m capkit workbook '{"path": "workbook/CapKit.xlsx"}'
python scripts/verify_workbook.py workbook/CapKit.xlsx --fuzz 10
- name: Checksums
run: |
(cd dist && sha256sum financing-true-cost.zip financing-true-cost.skill \
commercial-financing-disclosure.zip commercial-financing-disclosure.skill) > SHA256SUMS
(cd workbook && sha256sum CapKit.xlsx) >> SHA256SUMS
- name: Publish (fails if the release already exists; published assets are never replaced)
env:
GH_TOKEN: ${{ github.token }}
run: |
ASSETS="dist/financing-true-cost.zip dist/financing-true-cost.skill \
dist/commercial-financing-disclosure.zip dist/commercial-financing-disclosure.skill \
workbook/CapKit.xlsx"
workbook/CapKit.xlsx SHA256SUMS"
for f in $ASSETS; do test -f "$f" || { echo "missing $f"; exit 1; }; done
if ls dist | grep -q funding-mix-optimizer; then echo "frozen optimizer must not ship"; exit 1; fi
gh release create "$GITHUB_REF_NAME" $ASSETS --title "CapKit $GITHUB_REF_NAME" --generate-notes || \
gh release upload "$GITHUB_REF_NAME" $ASSETS --clobber
gh release create "$GITHUB_REF_NAME" $ASSETS --title "CapKit $GITHUB_REF_NAME" --generate-notes
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ dist/
.DS_Store
~$*.xlsx
skills/*/evals/results/
.hypothesis/
.coverage
.coverage.*
mutants/
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
# Changelog

## Unreleased

- Corrections that change a reported figure (each earlier figure was wrong):
- With `unit: "month"`, a single payment on a month end is measured in whole months: 1% for Jan 28 to
Feb 28 is 12.00%, not 10.90%.
- A monthly series on the 29th or 30th is recognised as monthly when the unit is inferred. Payments on
the 30th after a Dec 10 advance now use a monthly unit (22.19%) instead of five weeks (22.37%), and
such a series is no longer classed as having irregular payment periods.
- SBA 7(a) loans approved within 90 days: `prior_90_day_amount` and `prior_90_day_fee` go together, in
`sba_fee` and in an `sba_7a` offer. One without the other is now an error; before, a missing fee was
taken as $0 and a fee without an amount was ignored. The remaining fee ceiling is never negative.
- An equipment lease with no buyout and no `end_of_term` is reported as `lease_character_unknown`, not
as a nominal-buyout purchase. `end_of_term: "return"` with a buyout is an error.
- Every argument error from the JSON interface is a `ValueError` that names the argument. true/false is
never read as a number, dates must be `YYYY-MM-DD` on every Python version, and a whole number written
as `12.0` is accepted where a whole number is required.
- The average-period fallback of Appendix J (b)(4) rounds to any standard interval, including
multiples of a week or month (e.g. six weeks). Month-end anchoring follows the series: one mid-month
payment no longer shifts a month-end schedule, and an isolated month-end date is measured to the same
date.
- Loan payments are rounded to the nearest cent unless that would overpay into a refund on the final
payment (possible at high rates over long terms); the payment then rounds down. The workbook matches.
- Ordinary schedules (advances before payments) have exactly one solving rate; the solver bisects
instead of scanning, so a 20,000-debit schedule solves in about a second.
- The skills pass arguments as a JSON file on stdin and treat document text as data, never as
instructions. Released skills no longer include the workbook writer or a `python -m capkit` entry
point. Inputs and echoed errors are size-limited.
- Property-based tests (hypothesis) for the APR invariants and the JSON interface, end-to-end tests for
every command, a nightly deep-test workflow, and ruff/mypy/coverage gates in CI.

## 0.2.1

- Monthly positions use the payment series' nominal day of the month (Appendix J (b)(3)(iv)), so a
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Skills install by uploading the zip in Claude (Settings → Capabilities → Ski
- Regression tests cover the findings of two independent code audits.
- `scripts/verify_workbook.py` recalculates the workbook with an independent formula engine and
compares it with the Python engine on randomized inputs.
- CI runs the suite and the workbook check on Python 3.10 and 3.13.
- CI runs the suite and the workbook check on Python 3.9, 3.10 and 3.13.

```bash
pip install -r requirements-dev.txt
Expand Down
4 changes: 3 additions & 1 deletion docs/method.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ Each product carries a tax-character tag:
- **Interest**: deductible, subject to §163(j) unless exempt.
- **Character uncertain**: MCA and factoring costs, which depend on whether the deal is treated as a
sale of receivables or as debt.
- **Rent**: leases.
- **Rent**: true leases, where the equipment goes back (`end_of_term: "return"`).
- **Conditional sale likely**: a nominal ($1-out) buyout, or `end_of_term: "own"`. No after-tax figure.
- **Lease character unknown**: no buyout and no `end_of_term`. No after-tax figure until it is given.
- **Purchase cost**: forgone supplier discounts.

The after-tax figure applies a user-supplied marginal rate. Uncertain items show both treatments.
Expand Down
32 changes: 31 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "capkit"
version = "0.2.1"
description = "Tested small-business financing engine: Regulation Z Appendix J APRs for every product, CA/NY disclosure math, and a mixed-integer funding-mix optimizer, with a formula-verified Excel / Google Sheets workbook and Claude skills"
description = "Small-business financing cost engine: Regulation Z Appendix J APRs on actual dates, CA/NY disclosure math, a formula-verified workbook and Claude skills"
readme = "README.md"
requires-python = ">=3.9"
license = { text = "MIT" }
Expand All @@ -21,3 +21,33 @@ capkit = "capkit.api:main"

[tool.setuptools.packages.find]
where = ["src"]

[tool.ruff]
target-version = "py39"
line-length = 140
extend-exclude = ["skills/*/scripts/capkit"] # vendored copies of src/capkit

[tool.ruff.lint]
select = ["E", "F", "W", "B", "I", "UP", "RUF", "SIM", "PIE", "C4"]
ignore = [
"E741", # single-letter names follow the regulation's notation (A, P, t, f, i)
"RUF001", "RUF002", "RUF003", # typographic characters in docs/strings are intentional
"UP006", "UP007", "UP035", "UP045", # keep typing.List/Optional for Python 3.9 runtime annotations
"SIM108", # ternaries are not always clearer
"RUF005", # [a] + b list building is clearer here than unpacking
"E731", # small named lambdas define the equations being solved
]

[tool.ruff.lint.per-file-ignores]
"tests/*" = ["B011"]
"scripts/*" = ["E402"] # scripts put src/ on sys.path before importing capkit
"skills/*/scripts/*.py" = ["E402"] # generated skill entry points do the same for the vendored engine

[tool.mypy]
python_version = "3.9"
ignore_missing_imports = true
warn_unused_ignores = true
exclude = ["skills/"]
# third-party packages are runtime-optional and untyped here; their stubs (numpy >= 2.3 uses Python 3.12
# syntax) must not decide whether CapKit type-checks for 3.9
no_site_packages = true
4 changes: 4 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@ openpyxl>=3.1
scipy>=1.9
pytest>=7
formulas>=1.2
hypothesis>=6.100
ruff==0.17.6
mypy==1.19.1
coverage>=7
16 changes: 11 additions & 5 deletions scripts/build_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from capkit import api, params as P # noqa: E402
from capkit import api
from capkit import params as P

SKILLS = ROOT / "skills"
DIST = ROOT / "dist"
Expand Down Expand Up @@ -49,7 +50,8 @@ def _fmt(v):

def commands_md(names) -> str:
out = ["# Command reference", "",
"Run `python scripts/capkit_cli.py <command> '<json>'` (or `-` to read the JSON from stdin). "
"Write the arguments to a JSON file, then run `python scripts/capkit_cli.py <command> - < args.json`. "
"Never put text from a document on the command line. "
"Arguments not marked required are optional. Output is JSON: `{\"result\": ...}` or `{\"error\": ...}`.", ""]
for n in names:
d = api.describe(n)
Expand Down Expand Up @@ -86,22 +88,24 @@ def write(path: Path, text: str, check: bool, stale: list):
path.write_text(text)


FROZEN_PACKAGES = ("optimize", "verify") # the experimental optimizer ships only in its own skill
FROZEN_PACKAGES = ("optimize", "verify", "excel", "__main__.py")
# released skills ship only what their allow-listed commands use: no optimizer, no workbook writer, and no
# `python -m capkit` entry point that would bypass the allow-list


CLI_TEMPLATE = '''#!/usr/bin/env python3
"""Entry point for the {skill} skill (generated by scripts/build_skills.py). See SKILL.md.

python scripts/capkit_cli.py list
python scripts/capkit_cli.py describe <command>
python scripts/capkit_cli.py <command> '<json args>' (or '-' to read JSON from stdin)
python scripts/capkit_cli.py <command> - < args.json (JSON arguments on stdin)
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from capkit.api import main # noqa: E402 (vendored engine)
from capkit.api import main # vendored engine (E402 allowed in pyproject)

COMMANDS = {commands!r}

Expand All @@ -125,6 +129,8 @@ def diff(c):
return bool(c.left_only or c.right_only or c.diff_files) or any(diff(s) for s in c.subdirs.values())
if cmp is None or diff(cmp):
stale.append(str(dest.relative_to(ROOT)))
stale.extend(f"{(dest / name).relative_to(ROOT)} must not ship in a released skill"
for name in skip if (dest / name).exists())
return
if dest.exists():
shutil.rmtree(dest)
Expand Down
36 changes: 26 additions & 10 deletions scripts/verify_workbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

import formulas # noqa: E402
import formulas

from capkit import disclosures as D # noqa: E402
from capkit import params as P # noqa: E402
from capkit.products import analyze, early_pay_cost, factoring, mca_fixed, sba_7a, term_loan # noqa: E402
from capkit import disclosures as D
from capkit import params as P
from capkit.products import analyze, early_pay_cost, factoring, mca_fixed, sba_7a, term_loan

EXCEL_EPOCH = date(1899, 12, 30)

Expand Down Expand Up @@ -55,6 +55,11 @@ def run(self, inputs: dict, outputs: list):
return {o: sol[k].value[0, 0] for o, k in zip(outputs, outs)}


# outputs measured in dollars; every other numeric output is a rate, a count or a date serial
DOLLARS = {"finance_charge", "tl_payment", "tl_final", "sba_payment", "sba_final", "sba_fee", "sba_ceiling",
"fac_fee", "avg", "payment"}


class Checker:
def __init__(self, book):
self.book, self.n, self.fail = book, 0, []
Expand All @@ -67,7 +72,9 @@ def check(self, label, inputs, expected, tol=0.011):
if isinstance(exp, str):
ok = str(g) == exp
else:
ok = isinstance(g, (int, float)) and abs(float(g) - float(exp)) <= (tol if abs(exp) >= 1 else 1e-6)
# rates (and counts/serial dates, which are whole numbers) to 1e-6; dollar amounts to a cent
lim = tol if k[1] in DOLLARS else 1e-6
ok = isinstance(g, (int, float)) and abs(float(g) - float(exp)) <= lim
if not ok:
self.fail.append(f"{label}: {k[0]}.{k[1]} sheet={g!r} python={exp!r}")

Expand Down Expand Up @@ -109,19 +116,23 @@ def daily_cases(ch, rnd, n):

def loan_cases(ch, rnd, n):
S = "Loans"
cases = [(50000, 0.15, 24, 1500, 42548.02, 0.07)] + [
cases = [(50000, 0.15, 24, 1500, 42548.02, 0.07),
(500, 0.5833673019735014, 242, 0, 42548.02, 0.07)] + [ # cent rounding rounds down here
(rnd.uniform(1e4, 5e5), rnd.uniform(0.05, 0.3), rnd.choice([12, 24, 36, 60]), rnd.uniform(0, 5000),
rnd.choice([rnd.uniform(25e3, 50e3), rnd.uniform(5e4, 2.5e5), rnd.uniform(2.5e5, 3.5e5),
rnd.uniform(3.5e5, 3e6)]), rnd.uniform(0.04, 0.09)) for _ in range(n)]
for k, (amt, rate, months, fee, sba_amt, prime) in enumerate(cases):
sba_months = 120 if k == 0 else rnd.choice([12, 60, 120, 300])
tl = analyze(term_loan(amt, rate, months, fee))
tls = term_loan(amt, rate, months, fee)
tl = analyze(tls)
sb = sba_7a(sba_amt, prime=prime, months=sba_months)
sa = analyze(sb)
ch.check(f"Loans {amt:.0f}/{sba_amt:.0f}",
{(S, "tl_amount"): amt, (S, "tl_rate"): rate, (S, "tl_months"): months, (S, "tl_fee"): fee,
(S, "sba_amount"): sba_amt, (S, "prime"): prime, (S, "sba_months"): sba_months},
{(S, "tl_apr"): tl["apr_actuarial"], (S, "sba_fee"): sb.terms["upfront_fee"],
{(S, "tl_apr"): tl["apr_actuarial"], (S, "tl_payment"): tls.terms["payment"],
(S, "tl_final"): tls.terms["final_payment"], (S, "sba_payment"): sb.terms["payment"],
(S, "sba_final"): sb.terms["final_payment"], (S, "sba_fee"): sb.terms["upfront_fee"],
(S, "sba_ceiling"): P.sba_fee_ceiling(sba_amt), (S, "sba_apr"): sa["apr_actuarial"],
(S, "sba_rate"): sb.terms["annual_rate"], (S, "sba_fee_ok"): "OK"})

Expand Down Expand Up @@ -156,12 +167,17 @@ def disclosure_cases(ch, rnd, n):
est = D.estimate(fund, owed, split, avg, "business_day", d, fees, minp)
if est["estimated_term_days"] > 1090:
continue
# a disclosed APR near the estimate, so both "yes" and "no" verdicts are exercised; the sheet applies the
# regular (1/8 point) tolerance, so the engine's verdict is taken with irregular=False
disclosed = est["estimated_apr_actuarial"] * rnd.uniform(0.97, 1.01)
ok = D.check_disclosed_apr(disclosed, est, irregular=False)["methods"]["actuarial"]["consistent"]
ins = {(S, "funding"): fund, (S, "owed"): owed, (S, "fees"): fees, (S, "split"): split, (S, "window"): win,
(S, "fund"): xl_date(d), (S, "minpay"): minp}
(S, "fund"): xl_date(d), (S, "minpay"): minp, (S, "disclosed"): disclosed}
ins.update({(S, f"sales{k + 1}"): v for k, v in enumerate(sales)})
ch.check(f"Disclosure {fund:.0f} w{win}", ins,
{(S, "avg"): avg, (S, "payment"): est["first_payment"], (S, "n"): est["number_of_payments"],
(S, "term_days"): est["estimated_term_days"], (S, "apr"): est["estimated_apr_actuarial"]})
(S, "term_days"): est["estimated_term_days"], (S, "apr"): est["estimated_apr_actuarial"],
(S, "check"): "yes" if ok else "no"})


def main():
Expand Down
Loading
Loading