Sub topic 14
Optional: Scripting the Tie-Out Checks
Spreadsheet checks catch most errors while you build the tab. A short script adds a second line of defense. It reads the extracted numbers, runs the same tests every time, and fails loudly when a figure moves. This chapter shows how to export the tab, check it with pandas, and decide when scripting is worth the effort.
This chapter assumes you have finished the historical tab and its in-sheet checks from the integrity chapter. You should also know basic Python and what a pandas DataFrame is. It is optional. A model with a handful of years and one company can rely on the spreadsheet checks alone.
Why script a check you already have in Excel
The in-sheet checks (balance check, cash tie-out) only run when someone opens the file and looks at them. A script gives you several things the sheet does not:
- Repeatability. The same tests run on every company and every refresh, with no one forgetting a row.
- A record. The script output can be saved with the model, showing which tests passed and when.
- Scale. If you build tabs for ten companies, one script checks all ten.
- Independence. The script recomputes from raw inputs, so it catches a broken formula in the sheet itself, such as a total that was overwritten with a hardcoded number.
The cost is upkeep. The script depends on your row labels, so a layout change can break it. Keep it small and test only what matters.
Getting the data out of the sheet
Save the input section of the historical tab as a CSV file, with one row per line item and one column per fiscal year. Export the inputs and the reported totals, not your derived metrics. The script needs to compare what the company reported against what you computed.
A layout that works well:
| line_item | FY2022 | FY2023 | FY2024 |
|---|---|---|---|
| total_assets | 1000.0 | 1120.0 | 1240.0 |
| total_liabilities | 600.0 | 655.0 | 700.0 |
| total_equity | 400.0 | 465.0 | 540.0 |
Use plain, lowercase labels with underscores. Spaces and punctuation make lookups fragile. Keep the units the same as in the sheet, for example millions of dollars, and note them in the file name or in a comment in your script.
The balance check in pandas
The core test is the accounting identity: assets minus liabilities minus equity should be zero. Total equity here includes any noncontrolling interest. Reported figures are rounded, so allow a small tolerance instead of testing for exact zero.
import pandas as pd
bs = pd.DataFrame(
{
"FY2022": {"total_assets": 1000.0, "total_liabilities": 600.0, "total_equity": 400.0},
"FY2023": {"total_assets": 1120.0, "total_liabilities": 655.0, "total_equity": 465.0},
}
)
diff = bs.loc["total_assets"] - bs.loc["total_liabilities"] - bs.loc["total_equity"]
print(diff.abs().lt(0.5))The diff variable is a Series indexed by year. The lt(0.5) call returns True for each year where the absolute difference is under 0.5. With figures in millions, a tolerance of 0.5 allows for rounding in the report. If your figures are in thousands, scale the tolerance to match.
Both years print True here, so the balance sheet ties. A False means you should go back to the report and compare line by line.
Turning checks into a reusable function
A single printed line is easy to ignore. Wrap each test so it returns a clear pass or fail with the failing years named, and make the script exit with an error code when anything fails.
import sys
import pandas as pd
TOLERANCE = 0.5 # same units as the data, for example millions of dollars
def load_tab(path: str) -> pd.DataFrame:
"""Read the exported tab: line items as rows, fiscal years as columns."""
return pd.read_csv(path, index_col="line_item")
def check_balance(tab: pd.DataFrame) -> pd.Series:
diff = tab.loc["total_assets"] - tab.loc["total_liabilities"] - tab.loc["total_equity"]
return diff.abs() > TOLERANCE
def check_cash(tab: pd.DataFrame) -> pd.Series:
diff = tab.loc["cash_flow_ending_cash"] - tab.loc["balance_sheet_cash"]
return diff.abs() > TOLERANCE
def check_subtotal(tab: pd.DataFrame, parts: list, total: str) -> pd.Series:
diff = tab.loc[parts].sum() - tab.loc[total]
return diff.abs() > TOLERANCE
def report(name: str, failures: pd.Series) -> bool:
bad_years = list(failures[failures].index)
if bad_years:
print(f"FAIL {name}: {', '.join(bad_years)}")
return False
print(f"PASS {name}")
return True
def main(path: str) -> int:
tab = load_tab(path)
results = [
report("balance sheet balances", check_balance(tab)),
report("ending cash ties to balance sheet", check_cash(tab)),
report(
"current assets subtotal",
check_subtotal(tab, ["cash", "receivables", "inventory", "other_current"], "total_current_assets"),
),
]
return 0 if all(results) else 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))Run it with python tieout.py historicals.csv. The exit code is 0 when everything passes and 1 otherwise, so you can chain it in a shell script or a scheduled job. The check functions return True for a failure, which keeps the reporting code simple: the years where the value is True are the years that broke.
The subtotal check is the most useful general pattern. Add one call for each subtotal the company reports: current assets, total assets, current liabilities, gross profit, operating income and net income. Comparing your sum of components with the reported total proves that you entered every line.
Checking against the sheet's own formulas
The same logic applies to the derived metrics. The spreadsheet computes EBITDA as EBIT plus D&A. The script can recompute it from the inputs and compare it with the number the sheet shows, using a column you also export.
import pandas as pd
def check_ebitda(tab: pd.DataFrame) -> pd.Series:
recomputed = tab.loc["ebit"] + tab.loc["depreciation_amortization"]
return (recomputed - tab.loc["sheet_ebitda"]).abs() > 0.5Here sheet_ebitda is the value exported from the sheet's EBITDA row. A mismatch means a formula in the sheet was edited or overwritten. This is the check that most directly justifies the script, because it tests the sheet against itself.
Failure modes and edge cases
- Wrong sign conventions. If the sheet stores expenses as negatives and the script assumes positives, every subtotal fails. Settle the convention first and state it in a comment at the top of the script.
- Tolerance too tight or too loose. A tolerance of 0 fails on harmless rounding. A tolerance of 50 hides real errors. Set it to about half a unit of the smallest reported digit.
- Missing line items. A misspelled label raises a
KeyError. This is useful, because it stops the script instead of silently skipping a test. - Blank cells. Pandas reads them as
NaN, and any arithmetic involvingNaNreturnsNaN. A comparison withNaNreturnsFalse, so a blank year can look like a pass. Add a guard that fails when any required cell is missing. - Noncontrolling interest. If you list it separately from parent equity, include it in the equity total, or the balance check will fail by exactly that amount.
- Restated years. After a restatement, the prior-year column should hold the restated figures. If the script compares against an older export, expect differences that are not errors.
A guard for blank cells:
import pandas as pd
def check_complete(tab: pd.DataFrame, required: list) -> pd.Series:
missing = tab.loc[required].isna().any()
return missingBecause isna().any() returns True for each year with at least one blank required cell, this function follows the same convention as the other checks and plugs into report directly.
How the pieces fit
The diagram shows the flow from the sheet to a pass or fail result.
When scripting is worth it
| Situation | Script? |
|---|---|
| One company, three to five years, built once | Usually no. In-sheet checks are enough. |
| Updated each quarter or each year | Yes. The script catches changes after a refresh. |
| Several companies with the same layout | Yes. One script covers all of them. |
| Model reviewed by others | Yes. The output is evidence the tab ties. |
| Layout changes often | Maybe not. Upkeep may exceed the benefit. |
Summary
- A script re-runs the tie-out checks the same way every time and exits with an error code on failure.
- Export inputs and reported totals as a CSV with lowercase labels and one column per fiscal year.
- Use a tolerance to allow for rounding, and make every check return the failing years.
- Guard against blank cells, sign mismatches and misspelled labels.
- Treat the script as a check on internal consistency, not on correctness against the filing.
Exercise
Your script prints PASS for the balance check, but the exported CSV has a blank cell for FY2024 total_liabilities. Explain why the check might pass wrongly, and write the pandas line that would catch the problem.
Show answer
Arithmetic with a blank (NaN) gives NaN, and the comparison diff.abs() > TOLERANCE returns False for NaN. Since the check treats True as a failure, FY2024 is reported as not failing, so it looks like a pass. A completeness guard catches it: tab.loc[["total_assets", "total_liabilities", "total_equity"]].isna().any() returns True for any year with a missing required cell, and that result should be reported as a failure.
Exercise
Write a check function named check_gross_profit that fails any year where revenue minus costofgoodssold differs from the reported grossprofit by more than the tolerance. Follow the convention used in this chapter.
Show answer
def checkgrossprofit(tab: pd.DataFrame) -> pd.Series: diff = tab.loc["revenue"] - tab.loc["costofgoodssold"] - tab.loc["grossprofit"] return diff.abs() > TOLERANCE The function returns True for each year that fails, so it can be passed to report("gross profit ties", checkgrossprofit(tab)).