Skip to content

CLI

excel_model.cli

CLI entry point for excel-model.

build(spec, output, style, data, mode)

Build an Excel financial model from a YAML spec.

Source code in excel_model/cli.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
@main.command()
@click.option("--spec", required=True, type=click.Path(exists=True), help="Path to model spec YAML")
@click.option("--output", required=True, type=click.Path(), help="Path for output .xlsx file")
@click.option(
    "--style",
    required=False,
    type=click.Path(exists=True),
    help="Path to style config YAML (uses bundled defaults if omitted)",
)
@click.option("--data", required=False, type=click.Path(exists=True), help="Path to input data file")
@click.option(
    "--mode",
    required=True,
    type=click.Choice(["batch", "interactive"]),
    help="batch = JSON to stdout; interactive = verbose narrative",
)
def build(spec: str, output: str, style: str | None, data: str | None, mode: str) -> None:
    """Build an Excel financial model from a YAML spec."""

    def emit_error(message: str) -> None:
        if mode == "batch":
            click.echo(json.dumps({"status": "error", "message": message}))
        else:
            click.echo(f"ERROR: {message}", err=True)
        sys.exit(1)

    def emit_info(message: str) -> None:
        if mode == "interactive":
            click.echo(message)

    # Load spec
    emit_info(f"Loading model spec: {spec}")
    try:
        from excel_model.spec_loader import load_spec

        loaded_spec = load_spec(spec)
    except (FileNotFoundError, ValueError, KeyError) as e:
        emit_error(f"Failed to load spec: {e}")
        return  # unreachable, but keeps type checker happy

    # Validate spec
    emit_info("Validating model spec...")
    from excel_model.validator import validate_spec

    errors = validate_spec(loaded_spec)
    if errors:
        emit_error("Spec validation failed:\n" + "\n".join(f"  - {e}" for e in errors))
    emit_info(f"  Model type: {loaded_spec.model_type}")
    emit_info(f"  Title: {loaded_spec.title}")
    emit_info(f"  Currency: {loaded_spec.currency}")
    emit_info(
        f"  Periods: {loaded_spec.n_history_periods} history + {loaded_spec.n_periods} projection ({loaded_spec.granularity})"
    )
    emit_info(f"  Assumptions: {len(loaded_spec.assumptions)}")
    emit_info(f"  Line items: {len(loaded_spec.line_items)}")

    # Load style
    emit_info(f"Loading style config: {style or '(bundled defaults)'}")
    try:
        loaded_style = load_style(style)
    except StyleConfigError as e:
        emit_error(f"Failed to load style config: {e}")
        return

    # Load input data (optional)
    inputs = None
    if data:
        emit_info(f"Loading input data: {data}")
        try:
            from excel_model.loader import load

            value_cols = list(loaded_spec.inputs.value_cols.values())
            inputs = load(
                source_path=data,
                period_col=loaded_spec.inputs.period_col,
                value_cols=value_cols,
                sheet=loaded_spec.inputs.sheet,
            )
            emit_info(f"  Loaded {len(inputs.df)} rows")

            from excel_model.validator import validate_inputs_against_spec

            input_errors = validate_inputs_against_spec(loaded_spec, inputs)
            if input_errors:
                emit_error("Input data validation failed:\n" + "\n".join(f"  - {e}" for e in input_errors))
        except (FileNotFoundError, ValueError) as e:
            emit_error(f"Failed to load input data: {e}")

    # Build workbook
    emit_info("Building workbook...")
    try:
        from excel_model.excel_writer import build_workbook

        build_workbook(spec=loaded_spec, inputs=inputs, output_path=output, style=loaded_style)
    except ExcelModelError as e:
        emit_error(f"Failed to build workbook: {e}")
    except (ValueError, KeyError, FileNotFoundError) as e:
        emit_error(f"Failed to build workbook: {e}")

    output_path = str(Path(output).resolve())
    emit_info(f"Workbook saved to: {output_path}")

    if mode == "batch":
        click.echo(json.dumps({"status": "ok", "output": output_path}))

describe(spec, output_format)

Dry-run description of what build would produce.

Source code in excel_model/cli.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
@main.command()
@click.option("--spec", required=True, type=click.Path(exists=True), help="Path to model spec YAML")
@click.option("--format", "output_format", required=True, type=click.Choice(["text", "json"]), help="Output format")
def describe(spec: str, output_format: str) -> None:
    """Dry-run description of what build would produce."""
    # Load spec
    try:
        from excel_model.spec_loader import load_spec

        loaded_spec = load_spec(spec)
    except (FileNotFoundError, ValueError, KeyError) as e:
        click.echo(f"ERROR: Failed to load spec: {e}", err=True)
        sys.exit(1)

    # Validate spec
    from excel_model.validator import validate_spec

    errors = validate_spec(loaded_spec)

    # Build description
    from excel_model.time_engine import generate_periods

    try:
        periods = generate_periods(
            start_period=loaded_spec.start_period,
            n_periods=loaded_spec.n_periods,
            n_history=loaded_spec.n_history_periods,
            granularity=loaded_spec.granularity,
        )
    except ValueError:
        periods = []

    # Group assumptions by group
    assumption_groups: dict[str, list] = {}
    for a in loaded_spec.assumptions:
        assumption_groups.setdefault(a.group, []).append(a)

    # Group line items by section
    sections: dict[str, list] = {}
    for li in loaded_spec.line_items:
        sections.setdefault(li.section, []).append(li)

    description = {
        "model_type": loaded_spec.model_type,
        "title": loaded_spec.title,
        "currency": loaded_spec.currency,
        "granularity": loaded_spec.granularity,
        "start_period": loaded_spec.start_period,
        "n_history_periods": loaded_spec.n_history_periods,
        "n_periods": loaded_spec.n_periods,
        "total_periods": len(periods),
        "period_labels": [p.label for p in periods],
        "metadata": {
            "preparer": loaded_spec.metadata.preparer,
            "date": loaded_spec.metadata.date,
            "version": loaded_spec.metadata.version,
        },
        "assumptions_count": len(loaded_spec.assumptions),
        "assumption_groups": {
            group: [{"name": a.name, "value": a.value, "format": a.format} for a in assumptions]
            for group, assumptions in assumption_groups.items()
        },
        "line_items_count": len(loaded_spec.line_items),
        "sections": {
            section: [{"key": li.key, "label": li.label, "formula_type": li.formula_type} for li in items]
            for section, items in sections.items()
        },
        "scenarios": [{"name": s.name, "label": s.label} for s in loaded_spec.scenarios],
        "column_groups": [{"key": cg.key, "label": cg.label} for cg in loaded_spec.column_groups],
        "sheets_to_create": ["Assumptions", "Inputs", "Model"],
        "validation_errors": errors,
        "inputs": {
            "source": loaded_spec.inputs.source,
            "period_col": loaded_spec.inputs.period_col,
            "value_cols": dict(loaded_spec.inputs.value_cols),
        },
    }

    if output_format == "json":
        click.echo(json.dumps(description, indent=2))
    else:
        click.echo(f"Model: {loaded_spec.title}")
        click.echo(f"Type:  {loaded_spec.model_type}")
        click.echo(f"Currency: {loaded_spec.currency}")
        click.echo()
        click.echo(f"Periods ({loaded_spec.granularity}):")
        if loaded_spec.n_history_periods > 0:
            hist = [p.label for p in periods if p.is_history]
            click.echo(f"  History ({loaded_spec.n_history_periods}): {', '.join(hist)}")
        proj = [p.label for p in periods if not p.is_history]
        click.echo(f"  Projection ({loaded_spec.n_periods}): {', '.join(proj)}")
        click.echo()
        click.echo(f"Assumptions ({len(loaded_spec.assumptions)}):")
        for group, assumptions in assumption_groups.items():
            click.echo(f"  [{group}]")
            for a in assumptions:
                click.echo(f"    {a.name}: {a.value} ({a.format})")
        click.echo()
        click.echo(f"Line Items ({len(loaded_spec.line_items)}):")
        for section, items in sections.items():
            if section:
                click.echo(f"  [{section}]")
            for li in items:
                marker = " [subtotal]" if li.is_subtotal else (" [total]" if li.is_total else "")
                click.echo(f"    {li.label.strip()}: {li.formula_type}{marker}")
        if loaded_spec.scenarios:
            click.echo()
            click.echo(f"Scenarios ({len(loaded_spec.scenarios)}):")
            for s in loaded_spec.scenarios:
                overrides = ", ".join(f"{k}={v}" for k, v in s.assumption_overrides.items())
                override_str = f" (overrides: {overrides})" if overrides else ""
                click.echo(f"  {s.label}{override_str}")
        if errors:
            click.echo()
            click.echo(f"Validation errors ({len(errors)}):")
            for e in errors:
                click.echo(f"  - {e}")
        else:
            click.echo()
            click.echo("Validation: OK")

main()

YAML-driven Excel financial model generator.

Source code in excel_model/cli.py
13
14
15
@click.group()
def main() -> None:
    """YAML-driven Excel financial model generator."""

validate(spec, data)

Validate a model spec YAML file.

Source code in excel_model/cli.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@main.command()
@click.option("--spec", required=True, type=click.Path(exists=True), help="Path to model spec YAML")
@click.option(
    "--data", required=False, type=click.Path(exists=True), help="Optional input data file to validate column mapping"
)
def validate(spec: str, data: str | None) -> None:
    """Validate a model spec YAML file."""
    # Load spec
    try:
        from excel_model.spec_loader import load_spec

        loaded_spec = load_spec(spec)
    except (FileNotFoundError, ValueError, KeyError) as e:
        click.echo(f"ERROR: {e}")
        sys.exit(1)

    # Validate spec
    from excel_model.validator import validate_spec

    errors = validate_spec(loaded_spec)

    # Optionally validate input data columns
    if data:
        try:
            from excel_model.loader import load

            value_cols = list(loaded_spec.inputs.value_cols.values())
            inputs = load(
                source_path=data,
                period_col=loaded_spec.inputs.period_col,
                value_cols=value_cols,
                sheet=loaded_spec.inputs.sheet,
            )
            from excel_model.validator import validate_inputs_against_spec

            input_errors = validate_inputs_against_spec(loaded_spec, inputs)
            errors.extend(input_errors)
        except (FileNotFoundError, ValueError) as e:
            errors.append(f"Input data: {e}")

    if errors:
        for err in errors:
            click.echo(err)
        sys.exit(1)
    else:
        click.echo("OK")