Sub topic 13
Automating Checks with a Script
This chapter assumes you can read the three statements, build a balance check row in Excel, and write basic Python (lists, dictionaries, functions). It builds on the checks from earlier chapters: the balance check, the first imbalanced period, the size and sign of the difference, and the cash tie-out. Here you will move those checks out of the spreadsheet and into a script that runs the same way every time.
Why script the checks
A check row in Excel works well while you are looking at the sheet. It has limits:
- It only helps if someone looks at it. A flag in row 61 is easy to miss after a long editing session.
- It can be broken by the same edit that broke the model. If someone overwrites the check formula or deletes the row, the warning disappears.
- Interpreting the result is manual. You still have to work out which period failed first and what the size of the difference suggests.
A script reads the model's numbers from outside the workbook and applies the checks consistently. It can run after every change, on every scenario, and on every file in a folder. It does not replace the in-sheet check. It is a second, independent line of defense.
What the script checks
The script repeats three ideas you already know.
- Balance by period. Assets minus liabilities and equity must be zero within a tolerance, in every period.
- First failure. Report the earliest period that breaks. Later periods usually inherit the error, so the first one is where to start.
- Error signature. Compare the size of the difference with the sizes of the cash flow items. A flipped sign on an item of size x changes the balance by 2x. An item left out, or linked once instead of twice, changes it by x.
Step 1: Compute the imbalance for each period
Start with the numbers. In this example the model balances in 2024 and 2025, then goes wrong in 2026.
periods = ["2024", "2025", "2026", "2027"]
assets = [500.0, 560.0, 640.0, 735.0]
liab_equity = [500.0, 560.0, 630.0, 725.0]
tol = 0.01
diffs = [round(a - le, 2) for a, le in zip(assets, liab_equity)]
first_bad = next((p for p, d in zip(periods, diffs) if abs(d) > tol), None)
print(diffs) # [0.0, 0.0, 10.0, 10.0]
print(first_bad) # 2026Three details matter here.
round(..., 2)removes floating-point noise. Without it, a difference such as1.4e-14would look like a failure.- The tolerance is applied to the absolute value, so a difference of
-10.0fails just as10.0does. next(..., None)returnsNonewhen every period passes. Your code must handle that case, as shown later.
The difference stays at 10.0 in 2027. The error happened once, in 2026, and the balance sheet carried it forward. That is why the first failing period is the useful one to report.
Step 2: Shortlist causes from the size of the difference
Once you know the period and the size, compare the difference with the cash flow items for that period.
diff = 10.0
items = {"Change in inventory": 5.0, "Capex": 42.0, "Dividends": 7.0}
# A flipped sign on an item of size x changes the balance by 2x.
# An item left out or linked once instead of twice changes it by x.
flipped = [n for n, v in items.items() if abs(abs(diff) - 2 * abs(v)) < 0.005]
omitted = [n for n, v in items.items() if abs(abs(diff) - abs(v)) < 0.005]
print(flipped) # ['Change in inventory']
print(omitted) # []The difference of 10 equals twice the change in inventory (2 × 5). So a flipped sign on the inventory line is the first suspect. No item equals 10 on its own, so the "omitted" list is empty.
The comparison tolerance here is 0.005, half a cent, because the items are rounded to two decimals. Use a tolerance that suits the precision of your own data.
What the shortlist can and cannot tell you
The script produces suspects, not proof. Two limits are worth knowing.
- Coincidences happen. If several items have values that fit, the script lists all of them. You still open the model and check each one.
- Multiple errors can combine. Two errors of different sizes can add up to a number that matches nothing on the list, or match the wrong item. If the shortlist is empty, that does not mean the model is fine. It means the error is not a single simple one.
Step 3: Put it together in one function
The pieces above are written as loose statements. A function makes them reusable across files and scenarios. This version returns a structured result so other code can use it.
def check_balance(periods, assets, liab_equity, items, tol=0.01):
"""Return the first failing period and a shortlist of suspect items."""
diffs = [round(a - le, 2) for a, le in zip(assets, liab_equity)]
for period, diff in zip(periods, diffs):
if abs(diff) > tol:
break
else:
return {"ok": True, "diffs": diffs}
flipped = [n for n, v in items.items()
if abs(abs(diff) - 2 * abs(v)) < 0.005]
omitted = [n for n, v in items.items()
if abs(abs(diff) - abs(v)) < 0.005]
return {
"ok": False,
"diffs": diffs,
"first_bad": period,
"difference": diff,
"flipped_sign_suspects": flipped,
"omitted_item_suspects": omitted,
}
result = check_balance(
periods=["2024", "2025", "2026", "2027"],
assets=[500.0, 560.0, 640.0, 735.0],
liab_equity=[500.0, 560.0, 630.0, 725.0],
items={"Change in inventory": 5.0, "Capex": 42.0, "Dividends": 7.0},
)
print(result["ok"]) # False
print(result["first_bad"]) # 2026
print(result["flipped_sign_suspects"]) # ['Change in inventory']The for ... else form runs the else block only when the loop finishes without a break. In other words, every period passed. If a period fails, the loop stops there, and period and diff hold the values for that first failure.
Note that the items are the cash flow items for the failing period. When you read values from a workbook, take them from the same column as the failing period, not from a different year.
Step 4: Add the cash tie-out
The balance check can pass while a different error hides underneath, so add the cash reconciliation as a second check. Cash flow ending cash must equal balance sheet cash in every period.
def check_cash(periods, cf_ending_cash, bs_cash, tol=0.01):
"""Return periods where cash flow ending cash differs from balance sheet cash."""
out = []
for p, cf, bs in zip(periods, cf_ending_cash, bs_cash):
d = round(cf - bs, 2)
if abs(d) > tol:
out.append((p, d))
return out
print(check_cash(["2025", "2026"], [120.0, 150.0], [120.0, 145.0]))
# [('2026', 5.0)]This mirrors the spreadsheet formula =ROUND(C75-C5,2). If cash fails in the same period as the balance check, fix cash first. A cash mismatch usually explains the balance difference directly.
Reading values from the workbook
So far the numbers were typed in. In practice you read them from the file. A common approach uses the openpyxl library. The cells below use the row layout from the earlier formulas: total assets in row 30, total liabilities and equity as row 45 plus row 58. Adjust the row numbers to match your model.
from openpyxl import load_workbook
wb = load_workbook("model.xlsx", data_only=True)
ws = wb["Balance Sheet"]
periods = [ws.cell(row=2, column=c).value for c in range(3, 7)]
assets = [ws.cell(row=30, column=c).value for c in range(3, 7)]
liabilities = [ws.cell(row=45, column=c).value for c in range(3, 7)]
equity = [ws.cell(row=58, column=c).value for c in range(3, 7)]
liab_equity = [l + e for l, e in zip(liabilities, equity)]Two gotchas apply.
data_only=Truereturns the values Excel last calculated and saved. If the file was never saved after the latest edit, or was produced by another program, those cached values can be stale or missing (None). Open the file in Excel, recalculate, and save before running the script.- Column and row positions are hard-coded. If someone inserts a row, the script reads the wrong cells and may report a false pass. Prefer to find rows by their label text, or keep a small mapping of labels to rows at the top of the script and update it with the model.
Making the result impossible to ignore
A check is only useful if its failure is noticed. Some practical habits:
- Exit with a non-zero status when a check fails, so a build job or batch file stops. In Python, call
sys.exit(1). - Print the first failing period and the difference on one line, so it is easy to scan.
- Run the script on every scenario, not only the base case. Errors often appear only when a switch changes a branch of a formula.
- Keep the script next to the model and under version control, so changes to either are reviewed together.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| No rounding before comparing | Floating-point noise causes false failures | Round to two decimals, then apply the tolerance |
| Testing `diff > tol` instead of `abs(diff) > tol` | Negative imbalances pass | Always use the absolute value |
| Reading stale cached values | Script reports old results | Recalculate and save in Excel first |
| Hard-coded cell positions | Row insertions cause false passes | Look up rows by label |
| Treating the shortlist as proof | Wrong fix applied | Open the model and confirm the suspect |
| Reporting every failing period | Noise hides the origin | Report the first failing period |
Summary
A script repeats the same three checks every time: the balance by period, the first failing period, and the size of the difference compared with cash flow items. Add the cash tie-out as a second check. Treat the shortlist as a starting point for investigation. Read values carefully, because a script that reads the wrong cell is worse than no script.
Exercise
A model has periods 2025 to 2028, and the script reports differences of [0.0, -14.0, -14.0, -14.0]. The cash flow items for the failing period are: Change in receivables 7.0, Capex 30.0, Debt repayment 14.0. Which period does the script report as first bad, and which item is the most likely cause? Explain your reasoning, and say whether a check written as d > tol would have caught this.
Show answer
The first bad period is 2026, because it is the first with an absolute difference above the tolerance, and later periods inherit it. The absolute difference is 14. Two items fit. Change in receivables is 7, and 2 × 7 = 14, so a flipped sign on receivables fits. Debt repayment is 14, which equals the difference on its own, so an omitted or singly linked debt repayment also fits. Both are suspects, so open the model and check each item. A check written as d > tol would not have caught this, because the differences are negative. The check must use abs(d) > tol.
Exercise
Your script reads model.xlsx with data_only=True and reports that all periods balance. You then add a new row near the top of the balance sheet, and the script still reports a pass, even though you know a formula is broken. Give two reasons the script may be wrong and one way to guard against each.
Show answer
First, the cell positions are hard-coded, so after the row insertion the script reads the wrong rows. Guard against this by looking up rows by their label text. Second, with data_only=True the script reads cached values saved at the last calculation, which are stale if the file was not recalculated and saved after the edit. Guard against this by recalculating and saving in Excel before running the script. You can also test the script against a deliberately broken copy to confirm that it fails.