Dynamic PricingClickHouse Workshops

03 Find opportunities and compare prices

Find stock at risk, then use SQL to estimate how prices affect sales, waste, and profit.

Seu computador
Terminal do macOS: Execute os comandos do workshop no Terminal usando zsh ou bash.

Outcome

Identify a product with excess stock and run the price calculation yourself in ClickHouse SQL. Explain how different permitted prices could affect sales, unsold stock, and profit before expiry.

Starting point

Complete Module 02: Ingest sales and accelerate queries. Keep its automatically paced writer running. This module uses the sales stream, materialized views, and operational CDC data you prepared there.

Actions

1. Simulate a demand slowdown

A real-life example

Imagine heavy rain reduces lunchtime foot traffic near office buildings. Stores have already stocked sandwiches and rice bowls, but fewer customers arrive. More food may remain unsold before expiry, creating a reason to review prices.

In Opportunities, choose district 1 and select Reduce district demand by 50%. This is a simulation control: it makes generated shoppers less likely to buy from that district. Prices stay unchanged, and sales continue across the chain. The 50% setting creates a noticeable slowdown for the exercise; actual transaction counts vary.

Keep the writer running. A Demand slowdown progress panel appears automatically and records:

  • Selected at (wall-clock UTC): when the slowdown was requested.
  • Slowdown starts (business UTC): the point where new batches begin using reduced demand.
  • Full-window target (business UTC): the complete sales boundary needed for a full reduced-demand window.
  • A progress bar and the remaining business time, updated from complete data visible in ClickHouse.

The writer temporarily targets 20× business-clock speed until the target is reached, then returns to its previous pace. Fifteen business minutes target about 45 seconds of elapsed pacing, rather than a 15-minute pause. Generation and data delivery can take longer, so follow the progress panel instead of a stopwatch. The target rounds up to a complete business minute. Refreshing the page retains the original timestamps and progress. This accelerates simulation time; it is not a measured ClickHouse query speedup.

The query always looks back over the last 15 minutes of business time. As the window moves forward, sales from before the slowdown leave it and newer sales take their place.

Slowdown at simulated 02:20 UTC. At 02:25, the last 15 minutes contain 10 minutes before the change and 5 after. At 02:35, the whole window is after the change.

Follow the example: A slowdown starting at business time 02:20 reaches a full window at 02:35. At 02:25, the query still includes 10 minutes of earlier sales. These are business-clock times; automatic acceleration reaches them faster than your laptop clock. The progress panel calculates your own target, so you do not need to remember the start time or add 15 minutes yourself.

Watch recent_demand_factor and excess_units as new evidence arrives. They can change gradually rather than immediately after the click. The diagram shows which sales enter the calculation; actual demand and stock estimates depend on those sales.

2. Find products with excess stock

When the Demand slowdown progress panel says Ready to find pricing opportunities, run this query without replacing any values. While it fills, read the SQL explanation below; you do not need to pause for 15 elapsed minutes. If the panel reports a paused or disconnected writer, resume or restart it as indicated. A full window becomes ready only after complete, fresh evidence is visible in ClickHouse.

What the SQL does: WITH reads the current run and complete cutoff. pricing.retail_opportunities calculates demand and excess stock for district 1; ORDER BY and LIMIT 10 return the largest excess values.

The query gets a run and cutoff, calculates district-1 excess stock, then sorts and returns ten rows. Choose a ready row with positive excess.
WITH
    (SELECT tuple(run_id, cutoff)
     FROM pricing.retail_analysis_context LIMIT 1) AS context
SELECT
    tupleElement(context, 1) AS run_id,
    cutoff, store_id, sku, stock_units, base_demand_units,
    recent_demand_factor, excess_units, eligibility
FROM pricing.retail_opportunities(
    run = tupleElement(context, 1), district = 1,
    cutoff = tupleElement(context, 2))
ORDER BY excess_units DESC, store_id, sku
LIMIT 10;

Read recent_demand_factor alongside stock_units and excess_units. A demand factor below 1 indicates recent demand is below the historical reference. Positive excess units identify stock that projected sales at the current price would leave unsold before expiry.

Save the store and SKU of a row with eligibility = 'ready' and positive excess_units. Use that same product in the following SQL queries.

3. Inspect the inputs for your chosen product

Replace only 61 AS selected_store and 102 AS selected_sku with your chosen store and SKU. The query finds the run, district, and complete cutoff automatically.

What the SQL does: WHERE selects one store/product pair, and LIMIT 1 returns its stock, prices, costs, demand estimate, and scenario assumptions. This lets you inspect the inputs before calculating alternative prices.

The selected store and SKU are filtered to one input row containing stock, expiry, prices, costs, base demand, elasticity, and scenario assumptions.
WITH
    61 AS selected_store,
    102 AS selected_sku,
    (SELECT tuple(run_id, cutoff)
     FROM pricing.retail_analysis_context LIMIT 1) AS context
SELECT
    store_id, sku, cutoff, stock_units, expires_at,
    current_price_minor / 100 AS current_price_sgd,
    unit_cost_minor / 100 AS unit_cost_sgd,
    selling_cost_minor / 100 AS selling_cost_sgd,
    disposal_cost_minor / 100 AS disposal_cost_sgd,
    permitted_prices_minor, base_demand_units, elasticity,
    demand_multipliers, scenario_weights, model_version,
    inventory_version, price_version, eligibility
FROM pricing.retail_opportunities(
    run = tupleElement(context, 1),
    district = toUInt16(intDiv(selected_store - 1, 250) + 1),
    cutoff = tupleElement(context, 2))
WHERE store_id = selected_store AND sku = selected_sku
LIMIT 1;

Check eligibility = 'ready', then read these inputs:

InputMeaning in the calculation
stock_unitsMaximum units the store can sell from its current stock.
base_demand_unitsEstimated sales before expiry at the current price, using historical demand and recent sales.
elasticityPrepared price-response parameter used by pow(price / current_price, elasticity).
permitted_prices_minorPrices allowed by the current policy, in cents.
unit_cost_sgd, selling_cost_sgd, disposal_cost_sgdPurchase cost per starting unit, selling cost per sold unit, and disposal cost per unsold unit.
demand_multipliers, scenario_weightsSensitivity scenarios and their weights, which sum to 1.

Use the prepared model; inspect its assumptions

A price proposal is an alternative you have not applied. The prepared model estimates demand response to price from independent synthetic calibration observations. It uses a constrained Poisson model with price elasticity and calendar/exposure adjustments, then checks a later holdout period. You will use its parameters, not train it. ClickHouse expands the permitted prices and demand scenarios, caps each scenario at available stock, and aggregates expected economics. The scenarios test sensitivity; they are not confidence intervals.

4. Calculate the price alternatives yourself

Set the same two store/SKU values at the top, then run this complete statement in SQL console. It returns projected outcomes for every permitted price without changing operational stock or prices.

What the SQL does: It expands each permitted price into demand scenarios, caps each case at available stock, and combines the weighted results. It then calculates revenue, unsold stock, and profit change for each price and marks the best modeled result.

One ready product expands into six prices and eighteen price/scenario cases. SQL caps demand by stock, aggregates weighted sales, calculates economics, and ranks six projected price outcomes.
WITH
    61 AS selected_store,
    102 AS selected_sku,
    (SELECT tuple(run_id, cutoff)
     FROM pricing.retail_analysis_context LIMIT 1) AS context,
inputs AS (
    SELECT *
    FROM pricing.retail_opportunities(
        run = tupleElement(context, 1),
        district = toUInt16(intDiv(selected_store - 1, 250) + 1),
        cutoff = tupleElement(context, 2))
    WHERE store_id = selected_store AND sku = selected_sku
      AND eligibility = 'ready'
),
prices AS (
    SELECT *, arrayJoin(permitted_prices_minor) AS price_minor
    FROM inputs
),
scenarios AS (
    SELECT *, arrayJoin(arrayZip(demand_multipliers, scenario_weights)) AS scenario
    FROM prices
),
expected_sales AS (
    SELECT price_minor, current_price_minor, stock_units,
        unit_cost_minor, selling_cost_minor, disposal_cost_minor,
        sum(
            least(toFloat64(stock_units),
                base_demand_units * scenario.1 *
                pow(toFloat64(price_minor) / current_price_minor, elasticity)
            ) * scenario.2
        ) AS expected_units
    FROM scenarios
    GROUP BY price_minor, current_price_minor, stock_units,
        unit_cost_minor, selling_cost_minor, disposal_cost_minor
),
economics AS (
    SELECT *,
        stock_units - expected_units AS expected_unsold_units,
        expected_units * price_minor AS revenue_minor,
        expected_units * (price_minor - selling_cost_minor)
            - (stock_units - expected_units) * disposal_cost_minor AS net_recovery_minor,
        net_recovery_minor - stock_units * unit_cost_minor AS contribution_minor
    FROM expected_sales
)
SELECT
    selected_store AS store_id, selected_sku AS sku,
    tupleElement(context, 2) AS evidence_cutoff,
    stock_units, current_price_minor / 100 AS current_price_sgd,
    price_minor / 100 AS price_sgd,
    expected_units, expected_unsold_units,
    revenue_minor / 100 AS revenue_sgd,
    net_recovery_minor / 100 AS net_recovery_sgd,
    contribution_minor / 100 AS contribution_sgd,
    (net_recovery_minor - maxIf(net_recovery_minor,
        price_minor = current_price_minor) OVER ()) / 100 AS profit_change_sgd,
    row_number() OVER (ORDER BY net_recovery_minor DESC,
        price_minor = current_price_minor DESC, price_minor DESC) = 1 AS recommended
FROM economics
ORDER BY price_sgd DESC
LIMIT 100
SETTINGS use_query_cache = 0;

The calculation matches pricing.retail_price_comparison and the workbench. A runnable copy is in sql/retail/learner_price_comparison.sql.

Read the SQL one stage at a time:

StageWhat ClickHouse does
inputsReads one ready product using a complete run/cutoff boundary.
pricesUses arrayJoin to create one row for each permitted price.
scenariosUses arrayZip and arrayJoin to pair each demand multiplier with its weight and expand the cases.
expected_salesApplies price response, uses least to cap each case at available stock, then sums weighted demand.
economicsCalculates revenue, unsold units, selling/disposal costs, and contribution.
Final SELECTUses window functions to compare recovery with the unchanged price and identify the best permitted result.

Your action: Compare the current-price row with recommended = 1. Record expected units, expected unsold units, revenue, and profit change. Explain whether the extra sales compensate for the lower price.

Read the economics

Net recovery subtracts selling and disposal costs from receipts. Contribution also subtracts the purchase cost of all starting stock. Profit change compares contribution with unchanged pricing; starting purchase cost is constant across alternatives. A positive profit change can represent a smaller loss rather than positive total profit. Fractional expected units are weighted scenario averages. These are projections, not observed future sales.

Try another experiment: change available stock

Run this independent worked example in SQL console:

WITH 20 AS stock, 800 AS current_price, 16.0 AS base_demand, -2.0 AS elasticity
SELECT price,
 least(stock, base_demand * pow(price / current_price, elasticity)) AS units,
 stock - units AS waste,
 price * units - 20 * units - 50 * waste AS recovery_minor
FROM (SELECT arrayJoin([600,700,800]) AS price)
ORDER BY recovery_minor DESC;

For this example, SGD 7.00 sells 20 expected units and recovers 13,600 cents. SGD 8.00 sells 16 and recovers 12,280 cents. Change stock from 20 to 4 and rerun. Which price wins now?

Why lower price does not always help

A lower price can increase demand, but sales cannot exceed stock. When all prices sell the available units, the higher price recovers more. The SQL makes that constraint visible. arrayJoin expands the price array into rows; the remaining expressions run across those rows.

5. Verify the comparison in the workbench

In Opportunities, find the store and SKU you used in your SQL, then select Compare prices for Store … / SKU ….

ClickHouse price comparison for Store 61, SKU 102: 58 units in stock, current price SGD 9.00, and six permitted prices with projected sales, waste, recovery, and profit change. SGD 6.50 has the highest modeled recovery.

The workbench runs the same calculation you inspected above. In this example, six permitted prices and three demand scenarios produce 18 price/scenario combinations before weighted aggregation.

To compare exact values, run your manual query and open or refresh the workbench comparison immediately afterward. Confirm that store, SKU, evidence cutoff, stock, and current price match before comparing outcomes. If the live evidence advances, rerun both comparisons; numbers from different inputs can differ.

Read this screenshot:

MeasureKeep SGD 9.00Try SGD 6.50
Expected units sold before expiry8.113.5
Expected unsold units at expiry49.944.5
Net recovery after selling and disposal costsSGD 45.98SGD 62.56
Profit change versus keeping SGD 9.00SGD 0.00+SGD 16.57

The lower price earns less per unit but is projected to sell more units and leave less waste. The green row marks the highest modeled recovery among the permitted prices. Fractional units are weighted averages across scenarios. Money values are rounded independently for display.

Your action: Compare the current-price row with the green row. Explain the trade-off using expected sales, waste, and profit change. Keep the price unapplied until Module 04, which covers approval and observed sales. A Review SGD … button prepares a proposal; applying it requires the later Approve and apply price action.

Read the comparison's evidence time

The screenshot's comparison uses the 02:30 UTC evidence cutoff, even though Live business time (UTC) has advanced to 02:34. All price alternatives share those captured inputs. Refresh evidence runs a new comparison with newer inputs. The footer's 835 ms includes input capture and the comparison request; it is not a server-only benchmark.

What excess means

Excess units compare current stock with expected demand before expiry at the current price. The query combines exposure-adjusted historical sales, recent sales, current inventory, and the prepared price-response model. Missing or stale evidence produces an eligibility reason, not an invented forecast.

Verify

Identify the SQL that expands prices, caps demand at stock, and calculates profit change. Explain why a cheaper price can sell more units yet produce less profit, and why both comparisons need matching inputs. Save your selected product and recommendation for the next module.

Next: Apply and measure.

Nesta página

Acompanhar seu progresso?

Opcional. Enviaremos um link por e-mail para confirmar seu endereço; o progresso será registrado depois que você o abrir.

Use seu e-mail corporativo, não um endereço pessoal.

Ao continuar, você aceita os Termos.

PT