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
 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
122
123
124
125
126
127
128
129
@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:
        loaded_spec = load_spec(spec)
    except (FileNotFoundError, ValueError, KeyError) as e:
        emit_error(f"Failed to load spec: {e}")
        return  # pragma: no cover

    # Validate spec
    emit_info("Validating model 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  # pragma: no cover

    # Load input data (optional)
    inputs = None
    if data:
        emit_info(f"Loading input data: {data}")
        try:
            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")

            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:
        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
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
@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."""
    try:
        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)

    errors = validate_spec(loaded_spec)

    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,
    )

    description = _build_description(loaded_spec, periods, errors)

    if output_format == "json":
        click.echo(json.dumps(description, indent=2))
    else:
        click.echo(_render_description_text(description))

main()

YAML-driven Excel financial model generator.

Security: File path arguments (--spec, --data, --style, --output) are passed directly to the filesystem. Do not accept untrusted user input for these arguments without prior path validation and sanitization.

Source code in excel_model/cli.py
25
26
27
28
29
30
31
32
@click.group()
def main() -> None:
    """YAML-driven Excel financial model generator.

    Security: File path arguments (--spec, --data, --style, --output) are passed
    directly to the filesystem. Do not accept untrusted user input for these
    arguments without prior path validation and sanitization.
    """

validate(spec, data)

Validate a model spec YAML file.

Source code in excel_model/cli.py
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:
        loaded_spec = load_spec(spec)
    except (FileNotFoundError, ValueError, KeyError) as e:
        click.echo(f"ERROR: {e}")
        sys.exit(1)

    # Validate spec
    errors = validate_spec(loaded_spec)

    # Optionally validate input data columns
    if data:
        try:
            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,
            )
            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")