{"slug":"portfolio-analysis-from-the-free-sql-api","qid":"concentration","label":"Cumulative weight and the Herfindahl concentration index","post_title":"Portfolio Analysis in SQL: Weights to Drawdown","post_url":"/blog/portfolio-analysis-from-the-free-sql-api#q-concentration","columns":["ticker","weight_pct","cumulative_weight_pct","cumulative_hhi"],"rows":[{"ticker":"AAPL","weight_pct":25.71,"cumulative_weight_pct":25.71,"cumulative_hhi":661},{"ticker":"KO","weight_pct":16.55,"cumulative_weight_pct":42.26,"cumulative_hhi":935},{"ticker":"XOM","weight_pct":15.86,"cumulative_weight_pct":58.12,"cumulative_hhi":1186},{"ticker":"MSFT","weight_pct":15.08,"cumulative_weight_pct":73.2,"cumulative_hhi":1414},{"ticker":"JNJ","weight_pct":14.68,"cumulative_weight_pct":87.88,"cumulative_hhi":1629},{"ticker":"NVDA","weight_pct":12.12,"cumulative_weight_pct":100,"cumulative_hhi":1776}],"shape":"ranking","sql":"WITH holdings AS\n(\n    SELECT 'AAPL' AS ticker, 120 AS shares\n    UNION ALL SELECT 'MSFT', 45\n    UNION ALL SELECT 'NVDA', 80\n    UNION ALL SELECT 'KO',   300\n    UNION ALL SELECT 'JNJ',  90\n    UNION ALL SELECT 'XOM',  150\n),\nmarks AS\n(\n    SELECT\n        ticker,\n        argMax(toFloat64(close), (date, _ingest_time)) AS last_close\n    FROM global_markets.stocks_daily_aggs\n    WHERE ticker IN ('AAPL', 'MSFT', 'NVDA', 'KO', 'JNJ', 'XOM')\n      AND date >= today() - 30\n    GROUP BY ticker\n),\nweights AS\n(\n    SELECT\n        h.ticker AS ticker,\n        round(100 * (h.shares * m.last_close)\n              / sum(h.shares * m.last_close) OVER (), 4) AS weight_pct\n    FROM holdings AS h\n    INNER JOIN marks AS m ON m.ticker = h.ticker\n)\nSELECT\n    ticker,\n    round(weight_pct, 2) AS weight_pct,\n    round(sum(weight_pct) OVER (ORDER BY weight_pct DESC\n         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), 2) AS cumulative_weight_pct,\n    round(sum(pow(weight_pct, 2)) OVER (ORDER BY weight_pct DESC\n         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), 0) AS cumulative_hhi\nFROM weights\nORDER BY weight_pct DESC","computed_at":"2026-10-07T15:11:29.950807+00:00","elapsed":0.118042407}