Skip to main content
PYSPARK โ€ข LESSON 114

Moving Averages with Sliding Window Frames

How do we compute a 7-day trailing moving average of stock closing prices using relative row offsets?

Advancedโฑ 2 Minutesโญ 620 XP
๐Ÿค” THE QUESTION

How do we compute a 7-day trailing moving average of stock closing prices using relative row offsets?

๐Ÿ’ก WHAT IS IT?

Using rowsBetween(-6, Window.currentRow) to calculate a sliding aggregate across the 7 most recent trading days.

๐ŸŽฏ WHAT IS IT USED FOR?

Smoothing volatile time-series data, stock technical indicators, and demand trend forecasting.

๐Ÿ’ป EXAMPLE
from pyspark.sql.window import Window
from pyspark.sql.functions import avg, col

window_spec = Window.partitionBy("stock_symbol") \
    .orderBy("trade_date") \
    .rowsBetween(-6, Window.currentRow)

df = df.withColumn("7d_moving_avg", avg(col("close_price")).over(window_spec))

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Moving Averages with Sliding Window Frames.

  • โœ“ Define sliding window frame with rowsBetween(-6, currentRow)
  • โœ“ Compute moving average over window
  • โœ“ Smooth financial time-series trends