r/learnSQL • u/luckytrail924 • 5h ago
Two ways to measure monthly price changes in ClickHouse
Monthly return and monthly price range sound similar, but they answer different questions. Here’s an example using candlestick data, where each row represents one price bar for a contract.
1. Which months had the largest net price moves?
First, group by contract and month using toStartOfMonth(timestamp). Then use argMin(close, timestamp) and argMax(close, timestamp) to get the first and last closing prices.
Calculate the percentage change between them, then sort by ABS(return_pct) to find the largest moves in either direction.
The important detail is that the first closing price is not the monthly opening price. This measures the change between the first and last observed closes.
2. Which contracts had the widest price range within a month?
Instead of comparing endpoints, calculate MIN(close) and MAX(close) for each contract within the selected month.
Then calculate 100.0 * (max_close - min_close) / nullIf(min_close, 0).
This measures the range of closing prices relative to the minimum close. It does not capture intrabar highs and lows or tell you which extreme occurred first.
Why the distinction matters
A contract could start at 100, reach 130, and finish at 101. Its net return would be small, while its closing price range could be large.
Neither metric alone proves that the market was trending or ranging.
One filtering detail worth checking
You can use HAVING COUNT(*) > 5000 to exclude groups with fewer observations, but that threshold only makes sense for a specific bar interval and trading calendar. A high row count alone does not prove the data is complete.
For timestamp filtering, use timestamp >= month_start AND timestamp < next_month_start to avoid guessing the final timestamp of the month.
How would you check for missing bars before comparing these monthly results?