📈 Time Series Analysis in PySpark
Time Series Decomposition Architecture
Architecture Diagram
Detailed Explanation
What is Time Series Analysis?
Time series analysis involves analyzing time-ordered data points to extract meaningful statistics, identify patterns, and forecast future values. In PySpark, time series processing is parallelized across partitions, enabling analysis of petabyte-scale temporal datasets.
Key Takeaway: PySpark's distributed processing enables time series analysis at scales impossible with single-machine tools like pandas or R, while maintaining the same analytical rigor.
Temporal Windowing Operations
PySpark supports several windowing strategies for temporal aggregation:
| Window Type | Description | Use Case |
|---|---|---|
| Tumbling | Fixed-size, non-overlapping | Hourly/daily aggregations |
| Hopping | Fixed-size, periodic start | Rolling averages, overlapping aggregations |
| Session | Dynamic, activity-based | User session analytics |
| Sliding | Row-count or time-based | Moving averages, lag features |
Stationarity and Differencing
Most time series models require stationary data (constant mean and variance):
| Test | Null Hypothesis | p-value Threshold |
|---|---|---|
| ADF (Augmented Dickey-Fuller) | Unit root exists | p < 0.05 = stationary |
| KPSS | Series is stationary | p > 0.05 = stationary |
| Phillips-Perron | Unit root exists | p < 0.05 = stationary |
Differencing Techniques:
- First-order differencing:
- Seasonal differencing: where is the seasonal period
- Log transformation: Stabilizes variance for exponential growth patterns
Time Series Decomposition
Decomposition separates a time series into components:
| Component | Description | Detection Method |
|---|---|---|
| Trend | Long-term direction | Moving average, LOESS |
| Seasonal | Periodic patterns | Autocorrelation, spectral analysis |
| Residual | Unexplained noise | After removing trend and seasonality |
Model Selection:
- Additive: When seasonal variation is constant ()
- Multiplicative: When seasonal variation increases with level ()
Feature Engineering for Time Series
| Feature Type | Description | PySpark Function |
|---|---|---|
| Lag Features | Previous time step values | lag(col, n) |
| Rolling Statistics | Moving averages, std dev | avg(col).over(Window) |
| Calendar Features | Day of week, month, quarter | dayofweek(), month() |
| Exponential Weighted | Recency-weighted averages | ewm() |
| Fourier Features | Seasonal periodicity | sin(2πft), cos(2πft) |
Forecasting Methods
| Method | Complexity | Accuracy | Parallelizable |
|---|---|---|---|
| ARIMA | O(n²) | High | Limited |
| Prophet | O(n log n) | High | Yes |
| Random Forest | O(n log n) | Medium-High | Yes |
| Gradient Boosting | O(n log n) | High | Yes |
| Deep Learning | O(n × d) | Variable | Yes |
Best Practice: For distributed time series forecasting, prefer Prophet or ML-based approaches over ARIMA, which requires sequential processing.
Seasonal Patterns Detection
Autocorrelation Function (ACF):
- Measures correlation between a time series and its lagged values
- Significant spikes at lag indicate seasonality with period
Partial Autocorrelation Function (PACF):
- Measures direct correlation at each lag, removing intermediate effects
- Helps determine ARIMA order parameters (p, d, q)
Mathematical Foundations
Definition: Time Series
A time series is a sequence of observations indexed by time, where each represents the value at time .
ARIMA Model
The ARIMA(p, d, q) model combines autoregressive (AR), differencing (I), and moving average (MA) components:
where is the differenced series, are AR parameters, are MA parameters, and is white noise.
Stationarity Condition
A time series is weakly stationary if:
The Augmented Dickey-Fuller test statistic is:
Exponential Weighted Moving Average
EWMA gives exponentially decreasing weight to older observations:
where is the smoothing parameter.
Forecast Accuracy Metrics
| Metric | Formula | Range | Best For |
|---|---|---|---|
| MAE | [0, ∞) | Interpretable scale | |
| RMSE | [0, ∞) | Penalizes large errors | |
| MAPE | [0, 100%] | Scale-independent | |
| SMAPE | [0, 100%] | Symmetric errors |
Key Insight
Time series decomposition assumes the observed series is a combination of interpretable components. STL (Seasonal and Trend decomposition using Loess) is robust to outliers and handles any seasonal period, making it preferred over classical decomposition for production forecasting.
Summary
Time series analysis in PySpark combines distributed windowing operations for feature engineering with statistical models for forecasting. Stationarity testing (ADF/KPSS) determines differencing requirements. Decomposition separates trend, seasonality, and residuals for interpretable analysis. Forecast accuracy metrics (MAE, RMSE, MAPE) guide model selection.
Key Concepts Table
| Concept | Description | Performance Impact |
|---|---|---|
| Tumbling Window | Non-overlapping fixed-size intervals | O(n) processing per partition |
| Hopping Window | Periodic start with fixed size | O(n × window_size/step) |
| Lag Features | Previous time step values | O(n) with Window function |
| Rolling Aggregation | Moving statistics over window | O(n × window_size) |
| ADF Test | Augmented Dickey-Fuller stationarity test | O(n) with O(p) parameters |
| Seasonal Decomposition | Split into T+S+E components | O(n) with STL |
| Autocorrelation | Correlation at different lags | O(n × max_lag) |
| Prophet | Additive model with trend + seasonality | O(n log n) training |
| Calendar Features | Day/month/quarter encoding | O(n) computation |
| Fourier Features | Sinusoidal seasonality encoding | O(n × k) for k harmonics |
Code Examples
Temporal Windowing and Feature Engineering
# Save as script.py, then run:
spark-submit \
--master yarn \
--deploy-mode client \
--driver-memory 4g \
--executor-memory 8g \
--executor-cores 4 \
script.py
Seasonal Decomposition and Differencing
# Save as script.py, then run:
spark-submit \
--master yarn \
--deploy-mode client \
--driver-memory 4g \
--executor-memory 8g \
--executor-cores 4 \
script.py
ARIMA Model Fitting
# Save as script.py, then run:
spark-submit \
--master yarn \
--deploy-mode client \
--driver-memory 4g \
--executor-memory 8g \
--executor-cores 4 \
script.py
Prophet-like Distributed Forecasting
# Save as script.py, then run:
spark-submit \
--master yarn \
--deploy-mode client \
--driver-memory 4g \
--executor-memory 8g \
--executor-cores 4 \
script.py
Anomaly Detection in Time Series
# Save as script.py, then run:
spark-submit \
--master yarn \
--deploy-mode client \
--driver-memory 4g \
--executor-memory 8g \
--executor-cores 4 \
script.py
Performance Metrics
| Operation | 1K Points | 100K Points | 10M Points | 100M Points |
|---|---|---|---|---|
| Moving Average (window=24) | < 1 sec | 1-3 sec | 10-20 sec | 2-5 min |
| Lag Feature Generation | < 1 sec | 1-2 sec | 5-15 sec | 1-3 min |
| Seasonal Decomposition | < 1 sec | 2-5 sec | 30-60 sec | 5-10 min |
| ADF Stationarity Test | < 1 sec | < 1 sec | 1-3 sec | 5-10 sec |
| Autocorrelation (100 lags) | < 1 sec | 1-2 sec | 10-20 sec | 2-5 min |
| Prophet-style Decomposition | 1-3 sec | 10-20 sec | 2-5 min | 30-60 min |
| ARIMA Fitting (local) | 1-5 sec | 5-15 sec | 30-60 sec | 5-10 min |
| Anomaly Detection (ensemble) | < 1 sec | 2-5 sec | 20-40 sec | 3-8 min |
| Calendar Feature Extraction | < 1 sec | < 1 sec | 1-3 sec | 5-10 sec |
| Fourier Feature Generation | < 1 sec | 1-2 sec | 5-10 sec | 1-2 min |
Best Practices
- Always sort by timestamp before applying window functions to ensure correct temporal ordering across partitions
- Use
repartition(num_partitions, timestamp_column)to co-locate temporal data and reduce shuffle during window operations - Pre-filter time ranges before feature engineering to avoid computing lag/rolling features on unnecessary data
- Handle missing timestamps explicitly with
fillna()or interpolation—gaps in time series break window calculations - Use
pandas_udffor complex time series models (ARIMA, Prophet) that cannot be vectorized across partitions - Partition by time period (day, week, month) to enable partition pruning for time-range queries
- Cache intermediate DataFrames when performing multiple temporal analyses on the same dataset
- Avoid collecting large time series to the driver—use distributed algorithms for fitting models
- Use
approximatefunctions for real-time anomaly detection when exact quantiles are not required - Implement watermarking for streaming time series to handle late-arriving data gracefully
- Validate temporal ordering with
assert df.filter(col("ts") < lag("ts")).count() == 0before analysis - Use calendar table joins for complex date logic instead of chaining multiple date functions
See also: ML Pipeline Integration (24), ML Feature Engineering (32), Advanced Aggregations (31), Geospatial Data (27)
See Also
- ML Pipeline — Machine learning pipelines for forecasting
- ML Feature Engineering — Feature engineering techniques
- Advanced Aggregations — Aggregation patterns for temporal data
- Window Operations — Window functions for time-based analysis