Explain budget against actual line by line.
Done by an agent. Checked twice.
Budget against actual for every line, biggest gaps first, each large gap explained from the ledger entries behind it.
Real files in
- actuals.csv
Fifty-six ledger rows for the month, with a repeated row, refunds, two rows that are not coded to a real account and two budgeted accounts with nothing posted. 57 lines, 4 KB. - budget.csv
The month's budget for twenty-two of the accounts, two accounts have none. 23 lines, 515 bytes. - chart_of_accounts.csv
Twenty-four revenue and expense accounts. 25 lines, 734 bytes. - period.md
The month under review and the finance rule for which lines need explaining. 11 lines, 546 bytes.
Sample data written by Atris. Not a real company.
Three steps
- 1.Read the budget and the ledger
- 2.Work out and rank each variance
- 3.Write the result
Claude Sonnet 5.5, 51 seconds. No web. It never saw the check.
Checked twice
- Passed: 24 of 24 accounts in the chart appear once in variance.csv and 24 carry the name and type from the chart
- Passed: 24 of 24 actuals equal the sum of the ledger rows for the account, with the repeated row counted once
- Passed: 24 of 24 variances, percentages and favorable or unfavorable labels equal the ones recomputed
- Passed: 24 of 24 rows sit in rank order with the right rank number, largest variance first
- Passed: 12 of 12 lines over the finance rule are explained with ledger rows from their own account, 24 of 24 lines are marked correctly and the report gives 12 of 12 of them in rank order with budget, actual and variance
- Passed: variance_report.md states the net result: budget 15,600.00, actual -4,485.00, variance -20,085.00 and 2 of 2 rows for total revenue and total expense as budget, actual and variance
- Passed: 2 of 2 ledger rows with no valid account are reported as not coded with their amount and kept out of every line
- Passed: 121 of 121 figures in variance_report.md and 40 of 40 in the explanations equal a figure of the account or ledger row they sit beside, a sum of that account's ledger rows or a recomputed total
- Passed: 67 of 67 times a ledger row is cited, its amount or a total of the cited rows that includes it is written beside it
Second review by Claude Opus 5.5: pass.
Then we broke a copy of the output 6 ways on purpose. The check caught 6.
| | Budget | Actual | Variance | |---|---:|---:|---:| | Total revenue | 202,500.00 | 197,160.00 | -5,340.00 | | Total expense | 186,900.00 | 201,645.00 | 14,745.00 | | Net result (revenue minus expense) | 15,600.00 | -4,485.00 | -20,085.00 | Rule used: a line needs an explanation when its variance is 1,000.00 or more and 5.0 percent or more of budget (a line with no budget: 1,000.00 or more). Totals exclude the transactions not coded. ## Lines that need an explanation (largest variance first) **1. 4000 Clinic fees** (revenue): budget 182,000.00, actual 171,340.00, variance -10,660.00 (-5.9%), unfavorable.
How this was run
An AI agent on Claude Sonnet 5.5 was given a folder with the files below and a three-step flow, and nothing else. It had no web access and never saw the check. The check was written before the run and made stricter after it. It works the answer out again from the input files. Then Claude Opus 5.5 reviewed the result against the inputs. The input files are sample data written by Atris, with the problems a real week has planted in them.
Run 2 of 2 on 1 December 2026. The agent took 51 seconds. Run 1 passed both checks and the job was run again later. Each run starts clean. Between runs the written flow was made clearer, or a check was corrected or made stricter. Nobody edits the output.
What the second review verified
- Recomputed all 24 chart accounts from the input files (GL-3316 counted once; uncoded GL-3325 and GL-3341 left out). Budget, actual, variance, variance_pct, effect, explain flag and rank order all match variance.csv exactly, e.g. 4000 Clinic fees 182,000.00 / 171,340.00 / -10,660.00 / -5.9
- Totals in variance_report.md match the recomputation: revenue 202,500.00 / 197,160.00 / -5,340.00, expense 186,900.00 / 201,645.00 / 14,745.00, net 15,600.00 / -4,485.00 / -20,085.00, which is revenue minus expense
- Every txn_id cited in an explanation sits on its own account and the sums are correct, e.g. Clinic fees postings 44,180+45,260+43,975+41,890+2,235 = 177,540.00 and Product sales weeklies sum to 13,770.00
- Uncoded transactions are listed with txn_id and amount: GL-3325 1,260.00 (blank code) and GL-3341 340.00 (code 6999), 1,600.00 in total; 6800 and 6450 correctly use the stock 'No transactions were posted' sentence
What this run does not show
- The check tests that each explanation cites ledger rows from its own account with the right amounts and cannot tell whether it names the true cause.
- Any sum of an account's ledger rows is accepted as a figure in its explanation, so a wrong subtotal that equals another real subtotal would pass.
- The budget and ledger were written for this run with one clear story behind each large gap.
Would the check catch a wrong answer?
A check that cannot fail proves nothing. After the run we took a copy of the output, broke it one small way at a time and ran the check again. It caught 6 of 6. The check was made stricter after the first try at this, and the same untouched output was graded again.
Open every file
flow.md · the three steps the agent followed
# Explain budget against actual line by line function: finance for: the finance manager who presents the monthly numbers goal: Every budget line shows what was planned, what happened and the gap, biggest gaps first, with each large gap explained from the ledger. ## 1. Read the budget and the ledger Read input/period.md, input/chart_of_accounts.csv, input/budget.csv and input/actuals.csv. The actual for an account is the sum of its transactions. A row that repeats a txn_id counts once. An account in the chart with no budget row has a budget of 0.00. An account with no transactions has an actual of 0.00. A transaction whose account_code is blank or not in the chart belongs to no line: keep it out of every total and report it as not coded. ## 2. Work out and rank each variance For every account in the chart: - variance is actual minus budget. variance_pct is variance divided by budget times 100, to one decimal. Leave it blank when the budget is 0.00. - effect is `on_budget` when the variance is 0.00. Otherwise, for a revenue account, more than budget is `favorable` and less is `unfavorable`. For an expense account, less than budget is `favorable` and more is `unfavorable`. - explain is `yes` when the finance rule in period.md says the line needs an explanation, else `no`. Rank the lines by the size of the variance ignoring its sign, largest first. Break ties by account_code. For each line marked `yes`, write the explanation from the transactions on that account: name the transaction or transactions that cause the gap by txn_id with the amount and what the description says. Cite only txn_ids that sit on that account. If the account has no transactions, the explanation is `No transactions were posted to this account in the month.` Do not give a cause the descriptions do not state. ## 3. Write the result Write output/variance.csv with columns rank,account_code,account_name,type,budget,actual,variance,variance_pct,effect,explain,explanation. One row per account in rank order, money with two decimals. Leave explanation blank when explain is `no`. Write output/variance_report.md for the finance manager: total revenue, total expense and net result (revenue minus expense), each as budget, actual and variance. Then the lines marked `yes` in rank order with their explanations. Then the transactions that were not coded, with txn_id and amount. ## Done looks like - Every account in the chart appears once in variance.csv, largest variance first. - Every line that needs an explanation names real transactions from its own account. - The net result in variance_report.md equals revenue minus expense from variance.csv.
input/actuals.csv · 57 lines, 4 KB
txn_id,date,account_code,description,amount GL-3301,2026-11-02,6000,"Rent, three clinics, November",14000.00 GL-3302,2026-11-02,6250,"Clinic insurance, monthly instalment",2100.00 GL-3303,2026-11-02,6600,Ultrasound and shockwave machine leases,3150.00 GL-3304,2026-11-03,6100,"Booking system, monthly plan",1420.00 GL-3305,2026-11-03,6100,"Glyphworks notes software, monthly plan",990.00 GL-3306,2026-11-04,5200,"Halvorsen Medical, tape and strapping",1840.00 GL-3307,2026-11-05,6150,"Telephone and broadband, three clinics",950.00 GL-3308,2026-11-06,4000,"Clinic fees, week ending 6 November",44180.00 GL-3309,2026-11-06,4100,"Product sales, week ending 6 November",3310.00 GL-3310,2026-11-06,6200,"Search adverts, November",1450.00 GL-3311,2026-11-08,6400,"Mileage claims, home visits",865.00 GL-3312,2026-11-09,5300,"Stock purchases, supports and braces",4280.00 GL-3313,2026-11-09,6050,"Electricity, three clinics",1390.00 GL-3314,2026-11-10,5100,"Contractor clinicians, October hours invoiced",8900.00 GL-3315,2026-11-10,6300,Treatment couch servicing,740.00 GL-3316,2026-11-11,5200,"Halvorsen Medical, gloves and wipes",2110.00 GL-3316,2026-11-11,5200,"Halvorsen Medical, gloves and wipes",2110.00 GL-3317,2026-11-12,4900,"Local health grant, first instalment",2500.00 GL-3318,2026-11-12,6500,"Paper, toner and filing",560.00 GL-3319,2026-11-13,4000,"Clinic fees, week ending 13 November",45260.00 GL-3320,2026-11-13,4100,"Product sales, week ending 13 November",3540.00 GL-3321,2026-11-13,5000,"Payroll, first half November",47900.00 GL-3322,2026-11-13,5050,"Employer payroll taxes, first half",4870.00 GL-3323,2026-11-13,6200,Leaflet print run,1500.00 GL-3324,2026-11-14,4200,"Back care workshop, 32 places",3200.00 GL-3325,2026-11-15,,"Card payment, supplier not identified",1260.00 GL-3326,2026-11-16,6050,Water rates,850.00 GL-3327,2026-11-17,6100,"Glyph Works notes software, annual add-on for outcome tracking",2640.00 GL-3328,2026-11-18,4000,"Refunds, cancelled block bookings, Eastgate clinic closed 5 days for flood repair",-6200.00 GL-3329,2026-11-19,5200,"Halverson Medical, couch roll and gel",1975.00 GL-3330,2026-11-19,6300,"Emergency boiler replacement, Northgate clinic",4900.00 GL-3331,2026-11-20,4000,"Clinic fees, week ending 20 November",43975.00 GL-3332,2026-11-20,4100,"Product sales, week ending 20 November",3420.00 GL-3333,2026-11-20,6100,"Accounting software, monthly plan",930.00 GL-3334,2026-11-21,6700,"Agency fee, senior clinician hire",4800.00 GL-3335,2026-11-22,6400,"Rail fares, regional conference",1120.00 GL-3336,2026-11-23,5300,"Stock purchases, foam rollers and bands",3610.00 GL-3337,2026-11-23,6050,"Gas, catch-up bill after estimated readings",1480.00 GL-3338,2026-11-24,5100,"Contractor clinicians, November hours to date",9100.00 GL-3339,2026-11-24,6200,"Deposit returned, open day postponed to January",-800.00 GL-3340,2026-11-25,5200,"Dovecote Linen, towels",1555.00 GL-3341,2026-11-25,6999,"Parking permits, staff",340.00 GL-3342,2026-11-26,5100,"Locum cover, 3 weeks, maternity leave",8450.00 GL-3343,2026-11-26,6300,Door closer repair,600.00 GL-3344,2026-11-26,6500,"Reception chairs, two",455.00 GL-3345,2026-11-27,4000,"Clinic fees, week ending 27 November",41890.00 GL-3346,2026-11-27,4100,"Product sales, week ending 27 November",3500.00 GL-3347,2026-11-27,4100,Online shop launch week sales,3150.00 GL-3348,2026-11-27,5000,"Payroll, second half November",48350.00 GL-3349,2026-11-27,5050,"Employer payroll taxes, second half",4920.00 GL-3350,2026-11-27,5300,Stock for online shop launch,2120.00 GL-3351,2026-11-28,4200,"Running injury workshop, 32 places",3200.00 GL-3352,2026-11-30,4000,"Clinic fees, 28 to 30 November",2235.00 GL-3353,2026-11-30,6350,"Accountant, monthly retainer",2500.00 GL-3354,2026-11-30,6550,"Card processing fees, November",2760.00 GL-3355,2026-11-30,6550,Bank account fees,315.00
input/budget.csv · 23 lines, 515 bytes
account_code,month,budget 4000,2026-11,182000.00 4100,2026-11,14500.00 4200,2026-11,6000.00 5000,2026-11,96000.00 5050,2026-11,9800.00 5100,2026-11,18000.00 5200,2026-11,7200.00 5300,2026-11,8700.00 6000,2026-11,14000.00 6050,2026-11,2600.00 6100,2026-11,3400.00 6150,2026-11,950.00 6200,2026-11,5500.00 6250,2026-11,2100.00 6300,2026-11,1800.00 6350,2026-11,2500.00 6400,2026-11,1200.00 6450,2026-11,2000.00 6500,2026-11,800.00 6550,2026-11,2900.00 6600,2026-11,3150.00 6800,2026-11,4300.00
input/chart_of_accounts.csv · 25 lines, 734 bytes
account_code,account_name,type 4000,Clinic fees,revenue 4100,Product sales,revenue 4200,Workshop income,revenue 4900,Other income,revenue 5000,Salaries and wages,expense 5050,Payroll taxes,expense 5100,Contractor clinicians,expense 5200,Clinical supplies,expense 5300,Product cost of sales,expense 6000,Rent,expense 6050,Utilities,expense 6100,Software subscriptions,expense 6150,Telephone and internet,expense 6200,Marketing,expense 6250,Insurance,expense 6300,Repairs and maintenance,expense 6350,Professional fees,expense 6400,Travel,expense 6450,Training,expense 6500,Office supplies,expense 6550,Bank and card fees,expense 6600,Equipment leases,expense 6700,Recruitment,expense 6800,Depreciation,expense
input/period.md · 11 lines, 546 bytes
# Budget review Company: Castlereach Physiotherapy (an invented company, three clinics) Month: November 2026 Finance rule for this review: a line needs a written explanation when its variance is 1,000.00 or more in either direction and is also 5.0 percent or more of its budget. A line with no budget needs an explanation whenever its variance is 1,000.00 or more. Amounts in actuals.csv are positive for normal activity on the account (income on a revenue account, cost on an expense account) and negative for refunds, credits and reversals.
output/variance.csv · written by the agent, 25 lines
rank,account_code,account_name,type,budget,actual,variance,variance_pct,effect,explain,explanation 1,4000,Clinic fees,revenue,182000.00,171340.00,-10660.00,-5.9,unfavorable,yes,"Clinic fees are 10,660.00 under budget. GL-3328 (-6,200.00) is a refund of cancelled block bookings; its description says the Eastgate clinic was closed 5 days for flood repair. The five fee postings (GL-3308, GL-3319, GL-3331, GL-3345, GL-3352) total 177,540.00, which is 4,460.00 under budget; the descriptions give no reason for that part of the gap." 2,5100,Contractor clinicians,expense,18000.00,26450.00,8450.00,46.9,unfavorable,yes,"GL-3342 (8,450.00) is locum cover for 3 weeks of maternity leave, which equals the whole gap. GL-3314 (8,900.00, October hours invoiced) and GL-3338 (9,100.00, November hours to date) together equal the 18,000.00 budget." 3,6700,Recruitment,expense,0.00,4800.00,4800.00,,unfavorable,yes,"No budget for this account. GL-3334 (4,800.00) is an agency fee for a senior clinician hire." 4,6300,Repairs and maintenance,expense,1800.00,6240.00,4440.00,246.7,unfavorable,yes,"GL-3330 (4,900.00) is an emergency boiler replacement at the Northgate clinic. The other two postings, GL-3315 (740.00, treatment couch servicing) and GL-3343 (600.00, door closer repair), total 1,340.00, which is under the 1,800.00 budget." 5,6800,Depreciation,expense,4300.00,0.00,-4300.00,-100.0,favorable,yes,No transactions were posted to this account in the month. 6,6200,Marketing,expense,5500.00,2150.00,-3350.00,-60.9,favorable,yes,"Posted costs are GL-3310 (1,450.00, search adverts) and GL-3323 (1,500.00, leaflet print run), 2,950.00 in all, against a 5,500.00 budget. GL-3339 (-800.00) is a deposit returned because the open day was postponed to January. The descriptions do not say why the other spending is lower than budget." 7,6100,Software subscriptions,expense,3400.00,5980.00,2580.00,75.9,unfavorable,yes,"GL-3327 (2,640.00) is the annual add-on for outcome tracking on the Glyph Works notes software. The monthly plans GL-3304 (1,420.00), GL-3305 (990.00) and GL-3333 (930.00) total 3,340.00, which is under the 3,400.00 budget." 8,4900,Other income,revenue,0.00,2500.00,2500.00,,favorable,yes,"No budget for this account. GL-3317 (2,500.00) is the first instalment of a local health grant." 9,4100,Product sales,revenue,14500.00,16920.00,2420.00,16.7,favorable,yes,"GL-3347 (3,150.00) is online shop launch week sales. The four weekly postings (GL-3309, GL-3320, GL-3332, GL-3346) total 13,770.00, which is 730.00 under the 14,500.00 budget." 10,6450,Training,expense,2000.00,0.00,-2000.00,-100.0,favorable,yes,No transactions were posted to this account in the month. 11,5300,Product cost of sales,expense,8700.00,10010.00,1310.00,15.1,unfavorable,yes,"GL-3350 (2,120.00) is stock for the online shop launch. The other postings, GL-3312 (4,280.00, supports and braces) and GL-3336 (3,610.00, foam rollers and bands), total 7,890.00, which is under the 8,700.00 budget." 12,6050,Utilities,expense,2600.00,3720.00,1120.00,43.1,unfavorable,yes,"GL-3337 (1,480.00) is a catch-up gas bill after estimated readings. Electricity GL-3313 (1,390.00) and water rates GL-3326 (850.00) total 2,240.00, which is under the 2,600.00 budget." 13,6400,Travel,expense,1200.00,1985.00,785.00,65.4,unfavorable,no, 14,4200,Workshop income,revenue,6000.00,6400.00,400.00,6.7,favorable,no, 15,5200,Clinical supplies,expense,7200.00,7480.00,280.00,3.9,unfavorable,no, 16,5000,Salaries and wages,expense,96000.00,96250.00,250.00,0.3,unfavorable,no, 17,6500,Office supplies,expense,800.00,1015.00,215.00,26.9,unfavorable,no, 18,6550,Bank and card fees,expense,2900.00,3075.00,175.00,6.0,unfavorable,no, 19,5050,Payroll taxes,expense,9800.00,9790.00,-10.00,-0.1,favorable,no, 20,6000,Rent,expense,14000.00,14000.00,0.00,0.0,on_budget,no, 21,6150,Telephone and internet,expense,950.00,950.00,0.00,0.0,on_budget,no, 22,6250,Insurance,expense,2100.00,2100.00,0.00,0.0,on_budget,no, 23,6350,Professional fees,expense,2500.00,2500.00,0.00,0.0,on_budget,no, 24,6600,Equipment leases,expense,3150.00,3150.00,0.00,0.0,on_budget,no,
output/variance_report.md · written by the agent, 78 lines
# Budget against actual, November 2026 Castlereach Physiotherapy. Source: input/ files only. Variance is actual minus budget. ## Totals | | Budget | Actual | Variance | |---|---:|---:|---:| | Total revenue | 202,500.00 | 197,160.00 | -5,340.00 | | Total expense | 186,900.00 | 201,645.00 | 14,745.00 | | Net result (revenue minus expense) | 15,600.00 | -4,485.00 | -20,085.00 | Rule used: a line needs an explanation when its variance is 1,000.00 or more and 5.0 percent or more of budget (a line with no budget: 1,000.00 or more). Totals exclude the transactions not coded. ## Lines that need an explanation (largest variance first) **1. 4000 Clinic fees** (revenue): budget 182,000.00, actual 171,340.00, variance -10,660.00 (-5.9%), unfavorable. Clinic fees are 10,660.00 under budget. GL-3328 (-6,200.00) is a refund of cancelled block bookings; its description says the Eastgate clinic was closed 5 days for flood repair. The five fee postings (GL-3308, GL-3319, GL-3331, GL-3345, GL-3352) total 177,540.00, which is 4,460.00 under budget; the descriptions give no reason for that part of the gap. **2. 5100 Contractor clinicians** (expense): budget 18,000.00, actual 26,450.00, variance 8,450.00 (46.9%), unfavorable. GL-3342 (8,450.00) is locum cover for 3 weeks of maternity leave, which equals the whole gap. GL-3314 (8,900.00, October hours invoiced) and GL-3338 (9,100.00, November hours to date) together equal the 18,000.00 budget. **3. 6700 Recruitment** (expense): budget 0.00, actual 4,800.00, variance 4,800.00 (no budget), unfavorable. No budget for this account. GL-3334 (4,800.00) is an agency fee for a senior clinician hire. **4. 6300 Repairs and maintenance** (expense): budget 1,800.00, actual 6,240.00, variance 4,440.00 (246.7%), unfavorable. GL-3330 (4,900.00) is an emergency boiler replacement at the Northgate clinic. The other two postings, GL-3315 (740.00, treatment couch servicing) and GL-3343 (600.00, door closer repair), total 1,340.00, which is under the 1,800.00 budget. **5. 6800 Depreciation** (expense): budget 4,300.00, actual 0.00, variance -4,300.00 (-100.0%), favorable. No transactions were posted to this account in the month. **6. 6200 Marketing** (expense): budget 5,500.00, actual 2,150.00, variance -3,350.00 (-60.9%), favorable. Posted costs are GL-3310 (1,450.00, search adverts) and GL-3323 (1,500.00, leaflet print run), 2,950.00 in all, against a 5,500.00 budget. GL-3339 (-800.00) is a deposit returned because the open day was postponed to January. The descriptions do not say why the other spending is lower than budget. **7. 6100 Software subscriptions** (expense): budget 3,400.00, actual 5,980.00, variance 2,580.00 (75.9%), unfavorable. GL-3327 (2,640.00) is the annual add-on for outcome tracking on the Glyph Works notes software. The monthly plans GL-3304 (1,420.00), GL-3305 (990.00) and GL-3333 (930.00) total 3,340.00, which is under the 3,400.00 budget. **8. 4900 Other income** (revenue): budget 0.00, actual 2,500.00, variance 2,500.00 (no budget), favorable. No budget for this account. GL-3317 (2,500.00) is the first instalment of a local health grant. **9. 4100 Product sales** (revenue): budget 14,500.00, actual 16,920.00, variance 2,420.00 (16.7%), favorable. GL-3347 (3,150.00) is online shop launch week sales. The four weekly postings (GL-3309, GL-3320, GL-3332, GL-3346) total 13,770.00, which is 730.00 under the 14,500.00 budget. **10. 6450 Training** (expense): budget 2,000.00, actual 0.00, variance -2,000.00 (-100.0%), favorable. No transactions were posted to this account in the month. **11. 5300 Product cost of sales** (expense): budget 8,700.00, actual 10,010.00, variance 1,310.00 (15.1%), unfavorable. GL-3350 (2,120.00) is stock for the online shop launch. The other postings, GL-3312 (4,280.00, supports and braces) and GL-3336 (3,610.00, foam rollers and bands), total 7,890.00, which is under the 8,700.00 budget. **12. 6050 Utilities** (expense): budget 2,600.00, actual 3,720.00, variance 1,120.00 (43.1%), unfavorable. GL-3337 (1,480.00) is a catch-up gas bill after estimated readings. Electricity GL-3313 (1,390.00) and water rates GL-3326 (850.00) total 2,240.00, which is under the 2,600.00 budget. ## Transactions not coded These have a blank or unknown account code and are left out of every total. | txn_id | Amount | Account code | Description | |---|---:|---|---| | GL-3325 | 1,260.00 | (blank) | Card payment, supplier not identified | | GL-3341 | 340.00 | 6999 | Parking permits, staff | Total not coded: 1,600.00. ## Other notes - GL-3316 appears twice in actuals.csv with identical details; it is counted once (2,110.00). - Accounts 6800 Depreciation and 6450 Training have a budget but no postings; the files do not say whether the entries are still to come.
check.py · the check, written before the run
"""Recomputes every variance from the budget and the ledger and compares it with what the agent wrote."""
import csv, re, sys
from collections import defaultdict
from decimal import Decimal
from itertools import combinations
from pathlib import Path
root = Path(sys.argv[1]); ok = True
def say(passed, text):
global ok; ok = ok and passed; print(("PASS " if passed else "FAIL ") + text)
def money(s):
try: return round(float(str(s).replace(",", "").replace("$", "").replace("%", "").strip()), 2)
except ValueError: return None
# Figures in the written files. A figure is a number that is not part of an id or a date.
FIG = re.compile(r"(?<![\w.])(?<!\w-)(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?!\w|-\w)")
DAY = re.compile(r"\d{4}-\d{2}-\d{2}")
def dec(x): return abs(Decimal(str(x).replace(",", "").replace("$", "").strip()))
def figs(line): return [dec(m.group(0)) for m in FIG.finditer(line)]
def together(text, *vals):
"""True when one line of the text carries every one of these figures."""
return any(all(dec(v) in figs(ln) for v in vals) for ln in text.splitlines())
def writeup(text, id_re, rec, glob):
"""Every figure of two or more characters and every date must belong to a record named on its line
or to the facts that hold for the whole file. Returns how many were seen and the ones that do not."""
seen, bad = 0, []
for ln in text.splitlines():
allow = set(glob).union(*(rec[i] for i in re.findall(id_re, ln) if i in rec))
for t in [m.group(0) for m in FIG.finditer(ln) if len(m.group(0)) > 1] + DAY.findall(ln):
seen += 1
if (t if DAY.fullmatch(t) else dec(t)) not in allow: bad.append(t)
return seen, bad
def load(name): return list(csv.DictReader((root/"input"/name).open()))
chart = {r["account_code"]: r for r in load("chart_of_accounts.csv")}
budget = defaultdict(float)
for r in load("budget.csv"): budget[r["account_code"]] += float(r["budget"])
rule = (root/"input/period.md").read_text()
floor = float(re.search(r"variance is ([\d,]+\.\d{2}) or", rule).group(1).replace(",", ""))
pct_floor = float(re.search(r"([\d.]+) percent or more", rule).group(1))
actual, owner, seen, loose, txn = defaultdict(float), defaultdict(set), set(), {}, {}
for r in load("actuals.csv"):
if r["txn_id"] in seen: continue
seen.add(r["txn_id"]); txn[r["txn_id"]] = r
if r["account_code"].strip() not in chart: loose[r["txn_id"]] = float(r["amount"]); continue
actual[r["account_code"]] += float(r["amount"]); owner[r["account_code"]].add(r["txn_id"])
want = {}
for code, c in chart.items():
b, a = round(budget[code], 2), round(actual[code], 2); v = round(a - b, 2)
good = (v > 0) == (c["type"].strip() == "revenue")
eff = "on_budget" if v == 0 else ("favorable" if good else "unfavorable")
exp = abs(v) >= floor and (b == 0 or abs(v) / b * 100 >= pct_floor)
want[code] = {"b": b, "a": a, "v": v, "eff": eff, "exp": exp, "type": c["type"].strip()}
order = sorted(want, key=lambda k: (-abs(want[k]["v"]), k))
path = root/"output/variance.csv"
if not path.exists():
say(False, "output/variance.csv was not written"); sys.exit(1)
rows = list(csv.DictReader(path.open()))
got = {(r.get("account_code") or "").strip(): r for r in rows}
n = len(want)
named = sum(1 for k in want if k in got and (got[k].get("account_name") or "").strip() == chart[k]["account_name"].strip() and (got[k].get("type") or "").strip() == want[k]["type"])
say(set(got) == set(want) and len(rows) == n and named == n, f"{len(set(got) & set(want))} of {n} accounts in the chart appear once in variance.csv and {named} carry the name and type from the chart")
act = sum(1 for k, w in want.items() if k in got and money(got[k].get("actual")) == w["a"] and money(got[k].get("budget")) == w["b"])
say(act == n, f"{act} of {n} actuals equal the sum of the ledger rows for the account, with the repeated row counted once")
def pct_ok(g, w):
p = money(g.get("variance_pct") or "")
return (p is None and not (g.get("variance_pct") or "").strip()) if w["b"] == 0 else (p is not None and abs(p - w["v"] / w["b"] * 100) <= 0.051)
var = sum(1 for k, w in want.items() if k in got and money(got[k].get("variance")) == w["v"] and pct_ok(got[k], w) and (got[k].get("effect") or "").strip() == w["eff"])
say(var == n, f"{var} of {n} variances, percentages and favorable or unfavorable labels equal the ones recomputed")
seq = [(r.get("account_code") or "").strip() for r in rows]
placed = sum(1 for i, k in enumerate(order) if i < len(seq) and seq[i] == k and (rows[i].get("rank") or "").strip() == str(i + 1))
say(placed == n, f"{placed} of {n} rows sit in rank order with the right rank number, largest variance first")
need = [k for k in order if want[k]["exp"]]
flag = sum(1 for k, w in want.items() if k in got and ((got[k].get("explain") or "").strip().lower() == "yes") == w["exp"])
def explained(k):
text = (got.get(k, {}).get("explanation") or "")
cited = set(re.findall(r"GL-\d+", text))
if not owner[k]: return "no transactions" in text.lower() and not cited
return bool(cited) and cited <= owner[k]
exd = sum(1 for k in need if explained(k))
md = (root/"output/variance_report.md").read_text() if (root/"output/variance_report.md").exists() else ""
def spot(k): # the first line of the report that gives the account with its budget, actual and variance
w = want[k]
return next((i for i, ln in enumerate(md.splitlines()) if {dec(k), dec(w["b"]), dec(w["a"]), dec(w["v"])} <= set(figs(ln))), None)
spots = [spot(k) for k in need]
in_order = sum(1 for i, x in enumerate(spots) if x is not None and all(y is not None and y < x for y in spots[:i]))
say(flag == n and exd == len(need) and in_order == len(need), f"{exd} of {len(need)} lines over the finance rule are explained with ledger rows from their own account, "
f"{flag} of {n} lines are marked correctly and the report gives {in_order} of {len(need)} of them in rank order with budget, actual and variance")
nums = {abs(money(x)) for x in re.findall(r"\d[\d,]*\.\d{2}", md)}
def net(f): return round(sum(w[f] if w["type"] == "revenue" else -w[f] for w in want.values()), 2)
nb, na = net("b"), net("a")
def side(kind, f): return round(sum(w[f] for w in want.values() if w["type"] == kind), 2)
sides = [(side(k, "b"), side(k, "a"), round(side(k, "a") - side(k, "b"), 2)) for k in ("revenue", "expense")]
both = sum(1 for t in sides if together(md, *t))
say(abs(nb) in nums and abs(na) in nums and abs(round(na - nb, 2)) in nums and together(md, nb, na, round(na - nb, 2)) and both == 2,
f"variance_report.md states the net result: budget {nb:,.2f}, actual {na:,.2f}, variance {round(na - nb, 2):,.2f} and {both} of 2 rows for total revenue and total expense as budget, actual and variance")
lc = sum(1 for k, v in loose.items() if any(k in ln and dec(v) in figs(ln) for ln in md.splitlines()))
say(lc == len(loose) and not (set(loose) & {t for k in got for t in re.findall(r"GL-\d+", got[k].get("explanation") or "")}),
f"{lc} of {len(loose)} ledger rows with no valid account are reported as not coded with their amount and kept out of every line")
# What may be written beside an account: its own figures, its ledger rows, a sum of some of those rows
# and the gap between such a sum and the budget or the actual.
def near_pct(w):
if w["b"] == 0: return set()
p = w["v"] / w["b"] * 100
return {dec(f"{c:.1f}") for c in (round(p - 0.05, 1), round(p, 1), round(p + 0.05, 1)) if abs(c - p) <= 0.051}
def allowed(code):
w = want[code]; own = sorted(owner[code])
out = {dec(code), dec(w["b"]), dec(w["a"]), dec(w["v"]), dec(order.index(code) + 1), dec(len(own))} | near_pct(w)
for t in own: out |= set(figs(txn[t]["description"])) | {txn[t]["date"], dec(txn[t]["amount"])}
if len(own) <= 12:
for size in range(2, len(own) + 1):
for group in combinations(own, size):
tot = round(sum(float(txn[t]["amount"]) for t in group), 2)
out |= {dec(tot), dec(round(tot - w["b"], 2)), dec(round(tot - w["a"], 2)), dec(size)}
return out
rec = {code: allowed(code) for code in want}
for t, r in txn.items():
code = r["account_code"].strip()
rec[t] = {dec(r["amount"]), r["date"]} | set(figs(r["description"])) | set(figs(code)) | (rec[code] if code in want else set())
facts = set(figs(rule)) | {dec(x) for t in sides for x in t} | {dec(nb), dec(na), dec(round(na - nb, 2)), dec(n), dec(len(need)), dec(len(loose)),
dec(round(sum(loose.values()), 2)), dec(len(txn)), dec(sum(1 for w in want.values() if w["type"] == "revenue")), dec(sum(1 for w in want.values() if w["type"] == "expense"))}
ID = r"GL-\d+|(?<![\w.,-])\d{4}(?![\w.,-])"
seen_n, bad = writeup(md, ID, rec, facts)
seen2 = bad2 = 0
for k, g in got.items():
s2, b2 = writeup(g.get("explanation") or "", ID, rec, rec.get(k, set()))
seen2 += s2; bad2 += len(b2)
say(seen_n > 0 and not bad and bad2 == 0, f"{seen_n - len(bad)} of {seen_n} figures in variance_report.md and {seen2 - bad2} of {seen2} in the explanations equal a figure of the account or ledger row they sit beside, a sum of that account's ledger rows or a recomputed total")
# a ledger row that is cited must have its amount written beside it, or a total of cited rows that includes it
def backed(text):
cited = sorted({t for t in re.findall(r"GL-\d+", text) if t in txn}); have = set(figs(text)); cover = set()
for size in range(1, min(len(cited), 12) + 1):
for group in combinations(cited, size):
if dec(round(sum(float(txn[t]["amount"]) for t in group), 2)) in have: cover |= set(group)
return len(cited), len(cover)
c_all = c_ok = 0
for text in [g.get("explanation") or "" for g in got.values()] + md.splitlines():
a, b = backed(text); c_all += a; c_ok += b
say(c_all > 0 and c_ok == c_all, f"{c_ok} of {c_all} times a ledger row is cited, its amount or a total of the cited rows that includes it is written beside it")
sys.exit(0 if ok else 1)
actuals.csv: sample data written by Atris. Fingerprint 5ca710109fbc.
budget.csv: sample data written by Atris. Fingerprint 078f23b74583.
chart_of_accounts.csv: sample data written by Atris. Fingerprint 28973171ba05.
period.md: sample data written by Atris. Fingerprint f13157a7af63.
variance.csv: written by the agent. Fingerprint 7dde0dc3b6be.
variance_report.md: written by the agent. Fingerprint b422e8ddf54a.