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
 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
130
131
132
133
134
135
136
137
138
@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)

    try:
        emit_info(f"Loading model spec: {spec}")
        loaded_spec = _load_and_validate_spec(spec)
        emit_info("Validating model spec...")
        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)}")

        emit_info(f"Loading style config: {style or '(bundled defaults)'}")
        loaded_style = _load_style_config(style)

        inputs = None
        if data:
            emit_info(f"Loading input data: {data}")
            inputs = _load_input_data(loaded_spec, data)
            emit_info(f"  Loaded {len(inputs.df)} rows")

        emit_info("Building workbook...")
        build_workbook(spec=loaded_spec, inputs=inputs, output_path=output, style=loaded_style)
    except ExcelModelError as e:
        emit_error(str(e))
        return  # pragma: no cover
    except (ValueError, KeyError, FileNotFoundError) as e:
        emit_error(f"Failed to build workbook: {e}")
        return  # pragma: no cover

    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
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
@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
28
29
30
31
32
33
34
35
@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
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
170
171
172
173
174
175
@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."""
    try:
        loaded_spec = load_spec(spec)
    except (FileNotFoundError, ValueError, KeyError) as e:
        click.echo(f"ERROR: {e}")
        sys.exit(1)

    errors = validate_spec(loaded_spec)

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