How do we compute a 7-day trailing moving average of stock closing prices using relative row offsets?
Using rowsBetween(-6, Window.currentRow) to calculate a sliding aggregate across the 7 most recent trading days.
Smoothing volatile time-series data, stock technical indicators, and demand trend forecasting.
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))Practice typing production-grade PySpark code for Moving Averages with Sliding Window Frames.