콘텐츠로 이동
Data Prep
상세

시계열 분석 개요

시계열 분석(Time Series Analysis)은 시간 순서로 정렬된 데이터 포인트 \(\{x_t\}_{t=1}^T\)의 패턴을 분석하고 미래 값을 예측하는 분야다. 수요 예측, 주가 예측, 이상 탐지 등 다양한 비즈니스 문제에 적용됨.


이론적 기초

시계열 구성 요소

\[Y_t = T_t + S_t + C_t + I_t\]
구성요소 설명 특징
Trend (\(T_t\)) 장기적 증가/감소 추세 선형, 다항식, 지수
Seasonality (\(S_t\)) 고정 주기의 반복 패턴 일별, 주별, 월별, 연별
Cycle (\(C_t\)) 비고정 주기의 변동 경기 순환 등
Irregular (\(I_t\)) 불규칙 변동 (노이즈) 예측 불가

정상성 (Stationarity)

강정상성 (Strict Stationarity): 모든 \(t\), \(k\)에 대해 \((X_t, ..., X_{t+k})\)의 결합 분포가 동일

약정상성 (Weak Stationarity): - \(E[X_t] = \mu\) (상수) - \(Var(X_t) = \sigma^2\) (상수) - \(Cov(X_t, X_{t+h}) = \gamma(h)\) (시차에만 의존)

정상성 검정:

검정 귀무가설 특징
ADF (Augmented Dickey-Fuller) 단위근 존재 (비정상) 가장 널리 사용
KPSS 정상성 ADF와 함께 사용 권장
PP (Phillips-Perron) 단위근 존재 이분산성에 강건

자기상관 함수

ACF (Autocorrelation Function):

\[\rho(h) = \frac{\gamma(h)}{\gamma(0)} = \frac{Cov(X_t, X_{t+h})}{Var(X_t)}\]

PACF (Partial Autocorrelation Function):

\(X_t\)\(X_{t+h}\) 사이의 중간 시차 영향을 제거한 상관


알고리즘 분류 체계

Time Series Methods
├── Classical Statistical
│   ├── Exponential Smoothing (ETS)
│   │   ├── Simple (SES)
│   │   ├── Holt's Linear
│   │   └── Holt-Winters (Additive/Multiplicative)
│   ├── ARIMA Family
│   │   ├── AR, MA, ARMA
│   │   ├── ARIMA
│   │   ├── SARIMA
│   │   └── ARIMAX (with exogenous)
│   ├── State Space Models
│   │   ├── Kalman Filter
│   │   └── Structural Time Series
│   └── VAR (Vector Autoregression)
├── Machine Learning
│   ├── Tree-based
│   │   ├── XGBoost, LightGBM
│   │   └── Random Forest
│   ├── Feature Engineering Approach
│   └── Global Models
├── Deep Learning
│   ├── RNN-based
│   │   ├── LSTM
│   │   ├── GRU
│   │   └── DeepAR
│   ├── CNN-based
│   │   ├── TCN (Temporal Convolutional Network)
│   │   └── WaveNet
│   ├── Transformer-based
│   │   ├── Informer
│   │   ├── Autoformer
│   │   ├── FEDformer
│   │   ├── PatchTST
│   │   └── iTransformer
│   ├── MLP-based
│   │   ├── N-BEATS
│   │   ├── N-HiTS
│   │   └── TSMixer
│   └── Foundation Models
│       ├── TimeGPT
│       ├── Lag-Llama
│       └── Chronos
└── Hybrid / Ensemble
    ├── Prophet (Facebook)
    ├── NeuralProphet
    └── Model Averaging

통계적 방법

ARIMA (AutoRegressive Integrated Moving Average)

\[\phi(B)(1-B)^d X_t = \theta(B)\epsilon_t\]
  • AR(p): \(X_t = \sum_{i=1}^p \phi_i X_{t-i} + \epsilon_t\)
  • I(d): \(d\)차 차분으로 정상성 확보
  • MA(q): \(X_t = \epsilon_t + \sum_{j=1}^q \theta_j \epsilon_{t-j}\)

모수 선택: - ACF: MA 차수 결정 (ACF가 q 이후 절단) - PACF: AR 차수 결정 (PACF가 p 이후 절단) - AIC/BIC: 최적 모델 선택

from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.stattools import adfuller
import pmdarima as pm

# 정상성 검정
result = adfuller(series)
print(f'ADF Statistic: {result[0]:.4f}, p-value: {result[1]:.4f}')

# 자동 ARIMA (auto_arima)
model = pm.auto_arima(
    series,
    seasonal=True,
    m=12,  # 계절 주기
    stepwise=True,
    suppress_warnings=True,
    information_criterion='aic'
)
print(model.summary())

# 예측
forecast = model.predict(n_periods=30)

Exponential Smoothing (ETS)

Holt-Winters (Triple Exponential Smoothing):

\[\hat{y}_{t+h|t} = l_t + hb_t + s_{t+h-m(k+1)}\]
  • Level: \(l_t = \alpha(y_t - s_{t-m}) + (1-\alpha)(l_{t-1} + b_{t-1})\)
  • Trend: \(b_t = \beta(l_t - l_{t-1}) + (1-\beta)b_{t-1}\)
  • Seasonal: \(s_t = \gamma(y_t - l_{t-1} - b_{t-1}) + (1-\gamma)s_{t-m}\)

참고 논문: - Hyndman, R.J. et al. (2002). "A State Space Framework for Automatic Forecasting Using Exponential Smoothing Methods". IJF.


딥러닝 방법

LSTM (Long Short-Term Memory)

순환 구조로 시퀀스 패턴 학습:

$\(f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f)\)$ (Forget gate) $\(i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i)\)$ (Input gate) $\(\tilde{C}_t = \tanh(W_C \cdot [h_{t-1}, x_t] + b_C)\)$ (Candidate) $\(C_t = f_t * C_{t-1} + i_t * \tilde{C}_t\)$ (Cell state) $\(o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + b_o)\)$ (Output gate) $\(h_t = o_t * \tanh(C_t)\)$ (Hidden state)

Transformer 기반 모델

Informer (AAAI 2021): - ProbSparse Self-attention: \(O(L \log L)\) 복잡도 - Self-attention Distilling: 피라미드 구조로 차원 축소 - Generative Decoder: 한 번에 긴 시퀀스 예측

PatchTST (ICLR 2023): - 시계열을 패치로 분할 (ViT 영감) - Channel Independence: 변수별 독립 처리 - 더 긴 컨텍스트 활용 가능

iTransformer (ICLR 2024): - 기존: 시간축에 attention → 변수축에 attention으로 전환 - 시간 포인트를 토큰으로, 변수를 시퀀스로 처리 - 다변량 시계열에서 SOTA

# NeuralForecast 라이브러리 사용
from neuralforecast import NeuralForecast
from neuralforecast.models import NBEATS, NHITS, PatchTST, iTransformer

models = [
    NBEATS(h=24, input_size=168, max_steps=1000),
    NHITS(h=24, input_size=168, max_steps=1000),
    PatchTST(h=24, input_size=168, max_steps=1000),
]

nf = NeuralForecast(models=models, freq='H')
nf.fit(df=train_df)
forecasts = nf.predict()

N-BEATS / N-HiTS

N-BEATS (NeurIPS 2020): - 순수 MLP 기반 (RNN/Attention 없음) - 해석 가능한 구조 (Trend + Seasonality 분해) - Double Residual Stacking

N-HiTS (AAAI 2023): - 계층적 보간 (Hierarchical Interpolation) - 다중 스케일 처리 - N-BEATS보다 효율적

참고 논문: - Oreshkin, B.N. et al. (2020). "N-BEATS: Neural Basis Expansion Analysis for Interpretable Time Series Forecasting". ICLR. - Challu, C. et al. (2023). "N-HiTS: Neural Hierarchical Interpolation for Time Series Forecasting". AAAI. - Zhou, H. et al. (2021). "Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting". AAAI. - Nie, Y. et al. (2023). "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers". ICLR. - Liu, Y. et al. (2024). "iTransformer: Inverted Transformers Are Effective for Time Series Forecasting". ICLR.


Foundation Models (2024)

TimeGPT (Nixtla)

  • 대규모 시계열 데이터로 사전학습된 Foundation Model
  • Zero-shot / Few-shot 예측 가능
  • API 기반 서비스

Chronos (Amazon, 2024)

  • T5 기반 시계열 Foundation Model
  • 토큰화: 연속 값을 이산 토큰으로 변환
  • 다양한 도메인에서 강건한 성능

Lag-Llama

  • Llama 아키텍처 기반
  • Lag features를 활용한 확률적 예측

참고 논문: - Ansari, A.F. et al. (2024). "Chronos: Learning the Language of Time Series". arXiv. - Rasul, K. et al. (2024). "Lag-Llama: Towards Foundation Models for Probabilistic Time Series Forecasting". arXiv.


Prophet (Facebook/Meta)

비즈니스 시계열에 최적화된 Additive 모델:

\[y(t) = g(t) + s(t) + h(t) + \epsilon_t\]
  • \(g(t)\): 트렌드 (선형/로지스틱)
  • \(s(t)\): 계절성 (Fourier series)
  • \(h(t)\): 휴일/이벤트 효과

장점: - 결측치, 이상치에 강건 - 휴일/이벤트 효과 쉽게 반영 - 도메인 지식 주입 가능

from prophet import Prophet
import pandas as pd

# 데이터 준비 (ds, y 컬럼 필요)
df = pd.DataFrame({'ds': dates, 'y': values})

# 모델 학습
model = Prophet(
    yearly_seasonality=True,
    weekly_seasonality=True,
    daily_seasonality=False,
    changepoint_prior_scale=0.05  # 트렌드 변화 민감도
)

# 휴일 추가
model.add_country_holidays(country_name='KR')

model.fit(df)

# 예측
future = model.make_future_dataframe(periods=365)
forecast = model.predict(future)

# 시각화
model.plot(forecast)
model.plot_components(forecast)

참고 논문: - Taylor, S.J. & Letham, B. (2018). "Forecasting at Scale". The American Statistician.


평가 지표

지표 수식 특징
MAE $\frac{1}{n}\sum y_i - \hat{y}_i
RMSE \(\sqrt{\frac{1}{n}\sum(y_i - \hat{y}_i)^2}\) 큰 오차 페널티
MAPE $\frac{100}{n}\sum \frac{y_i - \hat{y}_i}{y_i}
SMAPE $\frac{100}{n}\sum\frac{ y_i - \hat{y}_i
MASE \(\frac{MAE}{MAE_{naive}}\) Naive 대비 상대 성능

실무 적용 가이드

방법 선택

시계열 예측 방법 선택
├── 데이터 양 < 1000개?
│   └── 통계적 방법 (ARIMA, ETS, Prophet)
├── 다변량 + 외부 변수 중요?
│   └── ML 방법 (XGBoost) 또는 딥러닝
├── 장기 예측 (>100 step)?
│   └── Transformer 기반 (Informer, PatchTST)
├── 해석 필요?
│   └── N-BEATS, Prophet
└── 빠른 프로토타입?
    └── Prophet, auto_arima

참고 문헌

교과서

  • Hyndman, R.J. & Athanasopoulos, G. (2021). "Forecasting: Principles and Practice" (3rd ed). OTexts. (무료)
  • Box, G.E.P. et al. (2015). "Time Series Analysis: Forecasting and Control". Wiley.

핵심 논문

  • Oreshkin, B.N. et al. (2020). "N-BEATS". ICLR.
  • Zhou, H. et al. (2021). "Informer". AAAI.
  • Nie, Y. et al. (2023). "PatchTST". ICLR.
  • Liu, Y. et al. (2024). "iTransformer". ICLR.
  • Taylor, S.J. & Letham, B. (2018). "Prophet". The American Statistician.

라이브러리

  • statsmodels: https://www.statsmodels.org/
  • Prophet: https://facebook.github.io/prophet/
  • NeuralForecast: https://github.com/Nixtla/neuralforecast
  • Darts: https://github.com/unit8co/darts
  • GluonTS: https://github.com/awslabs/gluonts