typestar

pl_sales_report.py in Python

Build a monthly sales summary from raw transactions.

"""Build a monthly sales summary from raw transactions with Polars."""
import polars as pl


def build_report(transactions):
    df = pl.DataFrame(transactions)
    return (
        df
        .with_columns(
            (pl.col("units") * pl.col("price")).alias("revenue"),
            pl.col("date").str.slice(0, 7).alias("month"),
        )
        .group_by("month", "product")
        .agg(
            pl.col("revenue").sum().round(2).alias("revenue"),
            pl.col("units").sum().alias("units"),
        )
        .sort("revenue", descending=True)
    )


def main():
    transactions = [
        {"date": "2026-06-03", "product": "kea", "units": 4, "price": 9.5},
        {"date": "2026-06-19", "product": "tui", "units": 2, "price": 12.0},
        {"date": "2026-07-02", "product": "kea", "units": 7, "price": 9.5},
        {"date": "2026-07-21", "product": "tui", "units": 5, "price": 12.0},
    ]
    report = build_report(transactions)
    print(report)
    print(f"total revenue: {report['revenue'].sum():.2f}")


if __name__ == "__main__":
    main()

How it works

  1. Expressions derive revenue and a month column.
  2. group_by aggregates revenue and units.
  3. The report sorts by revenue and totals it.

Keywords and builtins used here

The run, in numbers

Lines
35
Characters to type
897
Tokens
320
Three-star pace
115 tpm

At the three-star pace of 115 tokens a minute, this run takes about 167 seconds.

Type this snippet

Step 1 of 2 in Encore, step 31 of 32 in Polars.

← Previous Next →