validate_dcf.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. #!/usr/bin/env python3
  2. """
  3. DCF Model Validation Script
  4. Validates Excel DCF models for formula errors and common DCF mistakes
  5. """
  6. import sys
  7. import json
  8. from pathlib import Path
  9. class DCFModelValidator:
  10. """Validates DCF models for errors and quality issues"""
  11. def __init__(self, excel_path: str):
  12. try:
  13. import openpyxl
  14. except ImportError:
  15. raise ImportError("openpyxl not installed. Run: pip install openpyxl")
  16. self.excel_path = excel_path
  17. self.openpyxl = openpyxl
  18. if not Path(excel_path).exists():
  19. raise FileNotFoundError(f"File not found: {excel_path}")
  20. self.workbook_formulas = openpyxl.load_workbook(excel_path, data_only=False)
  21. self.workbook_values = openpyxl.load_workbook(excel_path, data_only=True)
  22. self.errors = []
  23. self.warnings = []
  24. self.info = []
  25. def validate_all(self) -> dict:
  26. """
  27. Run all validation checks
  28. Returns:
  29. Dict with validation results
  30. """
  31. from datetime import datetime
  32. self.check_sheet_structure()
  33. self.check_formula_errors()
  34. self.check_dcf_logic()
  35. results = {
  36. 'file': self.excel_path,
  37. 'validation_date': datetime.now().isoformat(),
  38. 'status': 'PASS' if len(self.errors) == 0 else 'FAIL',
  39. 'error_count': len(self.errors),
  40. 'warning_count': len(self.warnings),
  41. 'errors': self.errors,
  42. 'warnings': self.warnings,
  43. 'info': self.info
  44. }
  45. return results
  46. def check_sheet_structure(self):
  47. """Verify required sheets exist"""
  48. required_sheets = ['DCF', 'WACC', 'Sensitivity']
  49. sheet_names = self.workbook_values.sheetnames
  50. for sheet in required_sheets:
  51. if sheet not in sheet_names:
  52. self.warnings.append(f"Recommended sheet missing: {sheet}")
  53. else:
  54. self.info.append(f"Found sheet: {sheet}")
  55. def check_formula_errors(self):
  56. """Check for Excel formula errors in all sheets"""
  57. excel_errors = ['#VALUE!', '#DIV/0!', '#REF!', '#NAME?', '#NULL!', '#NUM!', '#N/A']
  58. error_details = {err: [] for err in excel_errors}
  59. total_errors = 0
  60. total_formulas = 0
  61. for sheet_name in self.workbook_values.sheetnames:
  62. ws_values = self.workbook_values[sheet_name]
  63. ws_formulas = self.workbook_formulas[sheet_name]
  64. for row in ws_values.iter_rows():
  65. for cell in row:
  66. formula_cell = ws_formulas[cell.coordinate]
  67. # Count formulas
  68. if formula_cell.value and isinstance(formula_cell.value, str) and formula_cell.value.startswith('='):
  69. total_formulas += 1
  70. # Check for errors
  71. if cell.value is not None and isinstance(cell.value, str):
  72. for err in excel_errors:
  73. if err in cell.value:
  74. location = f"{sheet_name}!{cell.coordinate}"
  75. error_details[err].append(location)
  76. total_errors += 1
  77. self.errors.append(f"{err} at {location}")
  78. break
  79. # Add summary info
  80. self.info.append(f"Total formulas: {total_formulas}")
  81. if total_errors == 0:
  82. self.info.append("✓ No formula errors found")
  83. else:
  84. self.errors.append(f"Total formula errors: {total_errors}")
  85. return error_details, total_errors
  86. def check_dcf_logic(self):
  87. """Validate DCF-specific logic and calculations"""
  88. self._check_terminal_growth_vs_wacc()
  89. self._check_wacc_range()
  90. self._check_terminal_value_proportion()
  91. def _check_terminal_growth_vs_wacc(self):
  92. """Critical check: Terminal growth must be less than WACC"""
  93. try:
  94. dcf_sheet = self.workbook_values['DCF']
  95. terminal_growth = None
  96. wacc = None
  97. # Search for terminal growth and WACC values
  98. for row in dcf_sheet.iter_rows(max_row=100, max_col=20):
  99. for cell in row:
  100. if cell.value and isinstance(cell.value, str):
  101. cell_str = cell.value.lower()
  102. if 'terminal' in cell_str and 'growth' in cell_str:
  103. # Look for value in adjacent cells
  104. for offset in range(1, 5):
  105. adjacent = dcf_sheet.cell(cell.row, cell.column + offset).value
  106. if isinstance(adjacent, (int, float)) and 0 < adjacent < 1:
  107. terminal_growth = adjacent
  108. break
  109. if 'wacc' in cell_str and wacc is None:
  110. for offset in range(1, 5):
  111. adjacent = dcf_sheet.cell(cell.row, cell.column + offset).value
  112. if isinstance(adjacent, (int, float)) and 0 < adjacent < 1:
  113. wacc = adjacent
  114. break
  115. if terminal_growth is not None and wacc is not None:
  116. if terminal_growth >= wacc:
  117. self.errors.append(
  118. f"CRITICAL: Terminal growth ({terminal_growth:.2%}) >= WACC ({wacc:.2%}). "
  119. "This creates infinite value and is mathematically invalid."
  120. )
  121. else:
  122. self.info.append(
  123. f"✓ Terminal growth ({terminal_growth:.2%}) < WACC ({wacc:.2%})"
  124. )
  125. else:
  126. self.warnings.append("Could not locate terminal growth and WACC values")
  127. except KeyError:
  128. self.warnings.append("DCF sheet not found")
  129. except Exception as e:
  130. self.warnings.append(f"Could not validate terminal growth vs WACC: {e!s}")
  131. def _check_wacc_range(self):
  132. """Check if WACC is in reasonable range"""
  133. try:
  134. wacc_sheet = self.workbook_values.get('WACC') or self.workbook_values['DCF']
  135. wacc = None
  136. for row in wacc_sheet.iter_rows(max_row=100, max_col=20):
  137. for cell in row:
  138. if cell.value and isinstance(cell.value, str):
  139. if 'wacc' in cell.value.lower():
  140. for offset in range(1, 5):
  141. adjacent = wacc_sheet.cell(cell.row, cell.column + offset).value
  142. if isinstance(adjacent, (int, float)) and 0 < adjacent < 1:
  143. wacc = adjacent
  144. break
  145. if wacc is not None:
  146. if wacc < 0.05 or wacc > 0.20:
  147. self.warnings.append(
  148. f"WACC ({wacc:.2%}) is outside typical range (5%-20%). Verify calculation."
  149. )
  150. else:
  151. self.info.append(f"✓ WACC ({wacc:.2%}) in reasonable range")
  152. else:
  153. self.warnings.append("Could not locate WACC value")
  154. except Exception as e:
  155. self.warnings.append(f"Could not validate WACC range: {e!s}")
  156. def _check_terminal_value_proportion(self):
  157. """Check if terminal value is reasonable proportion of enterprise value"""
  158. try:
  159. dcf_sheet = self.workbook_values['DCF']
  160. terminal_value = None
  161. enterprise_value = None
  162. for row in dcf_sheet.iter_rows(max_row=200, max_col=20):
  163. for cell in row:
  164. if cell.value and isinstance(cell.value, str):
  165. cell_str = cell.value.lower()
  166. if 'terminal' in cell_str and 'value' in cell_str and 'pv' in cell_str:
  167. for offset in range(1, 5):
  168. adjacent = dcf_sheet.cell(cell.row, cell.column + offset).value
  169. if isinstance(adjacent, (int, float)) and adjacent > 0:
  170. terminal_value = adjacent
  171. break
  172. if 'enterprise' in cell_str and 'value' in cell_str:
  173. for offset in range(1, 5):
  174. adjacent = dcf_sheet.cell(cell.row, cell.column + offset).value
  175. if isinstance(adjacent, (int, float)) and adjacent > 0:
  176. enterprise_value = adjacent
  177. break
  178. if terminal_value is not None and enterprise_value is not None and enterprise_value > 0:
  179. proportion = terminal_value / enterprise_value
  180. if proportion > 0.80:
  181. self.warnings.append(
  182. f"Terminal value is {proportion:.1%} of EV (typically should be 50-70%). "
  183. "Model may be over-reliant on terminal assumptions."
  184. )
  185. elif proportion < 0.40:
  186. self.warnings.append(
  187. f"Terminal value is {proportion:.1%} of EV (typically should be 50-70%). "
  188. "Check if terminal assumptions are too conservative."
  189. )
  190. else:
  191. self.info.append(f"✓ Terminal value is {proportion:.1%} of EV")
  192. else:
  193. self.warnings.append("Could not locate terminal value and enterprise value")
  194. except Exception as e:
  195. self.warnings.append(f"Could not validate terminal value proportion: {e!s}")
  196. def validate_dcf_model(excel_path: str) -> dict:
  197. """
  198. Validate a DCF model Excel file
  199. Args:
  200. excel_path: Path to Excel DCF model
  201. Returns:
  202. Dict with validation results
  203. """
  204. validator = DCFModelValidator(excel_path)
  205. return validator.validate_all()
  206. def main():
  207. """Command-line interface"""
  208. if len(sys.argv) < 2:
  209. print("Usage: python validate_dcf.py <excel_file> [output.json]")
  210. print("\nValidates DCF model for:")
  211. print(" - Formula errors (#REF!, #DIV/0!, etc.)")
  212. print(" - Terminal growth < WACC (critical)")
  213. print(" - WACC in reasonable range (5-20%)")
  214. print(" - Terminal value proportion of EV (40-80%)")
  215. print("\nReturns JSON with errors, warnings, and info")
  216. print("\nExample: python validate_dcf.py model.xlsx")
  217. print("Example: python validate_dcf.py model.xlsx results.json")
  218. sys.exit(1)
  219. excel_file = sys.argv[1]
  220. output_file = sys.argv[2] if len(sys.argv) > 2 else None
  221. try:
  222. results = validate_dcf_model(excel_file)
  223. # Print results
  224. print(json.dumps(results, indent=2))
  225. # Save to file if requested
  226. if output_file:
  227. with open(output_file, 'w') as f:
  228. json.dump(results, f, indent=2)
  229. # Exit with error code if validation failed
  230. sys.exit(0 if results['status'] == 'PASS' else 1)
  231. except Exception as e:
  232. error_result = {
  233. 'file': excel_file,
  234. 'status': 'ERROR',
  235. 'error': str(e)
  236. }
  237. print(json.dumps(error_result, indent=2))
  238. sys.exit(1)
  239. if __name__ == "__main__":
  240. main()