/* Serving mart: ICE certified Coffee C warehouse stocks by port, analytics-ready. */ /* End-of-month certified stock levels broken down by delivery port. */ /* Covers November 1996 to present (~30 years). Useful for understanding */ /* geographic shifts in the certified supply base over time. */ /* Source: ICE historical by-port XLS (EOM_KC_cert_stox_by_port_nov96-present.xls) */ /* Grain: one row per report_date (end-of-month). */
MODEL (
  name serving.ice_warehouse_stocks_by_port,
  kind INCREMENTAL_BY_TIME_RANGE (
    time_column report_date
  ),
  grain (
    report_date
  ),
  start '1996-11-01',
  cron '@daily'
);

WITH base AS (
  SELECT
    f.report_date,
    f.new_york_bags,
    f.new_orleans_bags,
    f.houston_bags,
    f.miami_bags,
    f.antwerp_bags,
    f.hamburg_bremen_bags,
    f.barcelona_bags,
    f.virginia_bags,
    f.total_bags,
    f.total_bags /* Month-over-month change in total certified bags */ - LAG(f.total_bags, 1) OVER (ORDER BY f.report_date) AS mom_change_bags,
    ROUND(
      (
        f.total_bags::DOUBLE - LAG(f.total_bags, 1) OVER (ORDER BY f.report_date)::DOUBLE
      ) / NULLIF(LAG(f.total_bags, 1) OVER (ORDER BY f.report_date)::DOUBLE, 0) * 100,
      2
    ) AS mom_change_pct, /* Month-over-month percent change */
    ROUND(
      AVG(f.total_bags::DOUBLE) OVER (ORDER BY f.report_date ROWS BETWEEN 11 PRECEDING AND CURRENT ROW),
      0
    ) AS avg_12m_bags, /* 12-month rolling average */
    f.source_file
  FROM foundation.fct_ice_warehouse_stocks_by_port AS f
  WHERE
    f.report_date BETWEEN @start_ds AND @end_ds
)
SELECT
  b.report_date,
  d.commodity_name,
  d.ice_stock_report_code,
  b.new_york_bags,
  b.new_orleans_bags,
  b.houston_bags,
  b.miami_bags,
  b.antwerp_bags,
  b.hamburg_bremen_bags,
  b.barcelona_bags,
  b.virginia_bags,
  b.total_bags,
  b.mom_change_bags,
  b.mom_change_pct,
  b.avg_12m_bags,
  b.source_file
FROM base AS b
CROSS JOIN foundation.dim_commodity AS d
WHERE
  d.ice_stock_report_code = 'COFFEE-C'
ORDER BY
  b.report_date