Moving Average

Time Series Analysis in PostgreSQL

Jasmin Ludolf

Content Developer, DataCamp

What is a moving average?

moving window

Time Series Analysis in PostgreSQL

Moving averages

  • Specify which rows to average
  • Using ROWS BETWEEN clause
  • UNBOUNDED PRECENDING AND CURRENT ROW: look at all previous rows from current row
SELECT 
id,
views,
AVG(views) OVER(
    PARTITION BY id
    ORDER BY ts
    ROWS BETWEEN
    UNBOUNDED PRECEDING AND CURRENT ROW)
    AS running_avg_views
FROM dc_news_fact;
Time Series Analysis in PostgreSQL

Calculate a moving average

  • Calculate the moving average for five rows:
    • ROWS BETWEEN 4 PRECEDING AND CURRENT ROW

 

(1) Row before

(2) Row before

(3) Row before

(4) Row before

(5) Current Row

Time Series Analysis in PostgreSQL

Calculate a moving average

SELECT
    id,
    ts,
    views,

AVG(views) OVER (
ORDER BY ts
ROWS BETWEEN 4 PRECEDING AND CURRENT ROW) AS moving_average_five
FROM dc_news_fact;
Time Series Analysis in PostgreSQL

Calculate a moving average: result

|   id|                 ts|views|moving_average_five|
|-----|-------------------|-----|-------------------|
|12121|2015-12-27 17:14:16| null|               null|
|12121|2015-12-27 17:34:16|   23|  23.00000000000000|
|12121|2015-12-27 17:54:16|   10|  16.50000000000000|
|12121|2015-12-27 18:14:16|    8|  13.66666666666666|
|12121|2015-12-27 18:34:16|    4|  11.25000000000000|
|12121|2015-12-27 18:54:16|    7|  10.40000000000000|
|12121|2015-12-27 19:14:16|    0| 5.8000000000000000|
...
Time Series Analysis in PostgreSQL

Calculate a moving average without current row

  • ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING
SELECT
    stock_symbol,
    day,
    daily_avg,
    AVG(daily_avg) OVER(
        PARTITION BY stock_symbol
        ORDER BY day
        ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING
        ) AS avg_prev_five
FROM daily_stock_averages
ORDER BY stock_symbol, day;
Time Series Analysis in PostgreSQL

Let's practice!

Time Series Analysis in PostgreSQL

Preparing Video For Download...