ARIMA
AutoRegressive Integrated Moving Average
A traditional time series forecasting model. Assumes stationarity.
AutoRegressive Integrated Moving Average
A traditional time series forecasting model. Assumes stationarity.
ARIMA (AutoRegressive Integrated Moving Average) is a statistical model that analyzes patterns in time series data and predicts future values. In ARIMA(p, d, q), p represents the autoregressive (AR) order, d represents the number of times differencing is applied, and q represents the moving average (MA) order. It is widely used to forecast data that changes over time, such as stock prices, sales, and temperature.
ARIMA was systematized by Box and Jenkins in the 1970s, which is why it is also called the "Box-Jenkins methodology." It established itself as an innovative methodology in economic forecasting and quality control at the time, and even 50 years later it is still used as a basic tool for time series analysis. Although deep learning-based time series models (LSTM, Transformer) have emerged, ARIMA is still preferred when data is scarce or interpretability is important.
The key step in ARIMA modeling is ensuring stationarity. If a time series has a trend or seasonality, it is converted into a stationary series through differencing. Stationarity is verified with the ADF (Augmented Dickey-Fuller) test, and the p and q values are estimated with ACF/PACF plots. If there is seasonality, SARIMA (Seasonal ARIMA) is used.
In practice, ARIMA is used for short-term demand forecasting, inventory management, and financial risk analysis. Its advantages are that it is interpretable, provides confidence intervals, and works with small amounts of data. Its disadvantages are that it has difficulty capturing nonlinear patterns and it is hard to directly incorporate external variables (holidays, events). To compensate for this, consider extended models such as ARIMAX or Prophet.
"""
ARIMA 시계열 예측 예제
statsmodels와 pmdarima를 활용한 자동 파라미터 선택 및 예측
"""
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.stattools import adfuller
import pmdarima as pm
import warnings
warnings.filterwarnings('ignore')
# 샘플 데이터 생성 (월별 매출 데이터 시뮬레이션)
np.random.seed(42)
dates = pd.date_range(start='2020-01-01', periods=48, freq='M')
trend = np.linspace(100, 200, 48)
seasonality = 20 * np.sin(np.linspace(0, 8*np.pi, 48))
noise = np.random.normal(0, 10, 48)
sales = trend + seasonality + noise
df = pd.DataFrame({'date': dates, 'sales': sales})
df.set_index('date', inplace=True)
print("=== 시계열 데이터 ===")
print(df.tail())
# 1. 정상성 검정 (ADF Test)
def check_stationarity(series):
result = adfuller(series)
print(f"\nADF Statistic: {result[0]:.4f}")
print(f"p-value: {result[1]:.4f}")
if result[1] < 0.05:
print("결론: 정상 시계열 (p < 0.05)")
return True
else:
print("결론: 비정상 시계열 - 차분 필요")
return False
print("\n=== 정상성 검정 ===")
is_stationary = check_stationarity(df['sales'])
# 2. Auto ARIMA로 최적 파라미터 자동 탐색
print("\n=== Auto ARIMA 파라미터 탐색 ===")
auto_model = pm.auto_arima(
df['sales'],
start_p=0, max_p=5,
start_q=0, max_q=5,
d=None, # 자동으로 차분 횟수 결정
seasonal=True, m=12, # 12개월 주기 계절성
start_P=0, max_P=2,
start_Q=0, max_Q=2,
trace=False,
error_action='ignore',
suppress_warnings=True,
stepwise=True
)
print(f"최적 모델: ARIMA{auto_model.order} x SARIMA{auto_model.seasonal_order}")
print(f"AIC: {auto_model.aic():.2f}")
# 3. 모델 학습 및 예측
train = df['sales'][:-6] # 마지막 6개월을 테스트로
test = df['sales'][-6:]
model = ARIMA(train, order=auto_model.order,
seasonal_order=auto_model.seasonal_order)
fitted = model.fit()
# 예측 (6개월)
forecast = fitted.get_forecast(steps=6)
predictions = forecast.predicted_mean
conf_int = forecast.conf_int()
print("\n=== 예측 결과 ===")
results = pd.DataFrame({
'실제값': test.values,
'예측값': predictions.values,
'하한(95%)': conf_int.iloc[:, 0].values,
'상한(95%)': conf_int.iloc[:, 1].values
}, index=test.index)
print(results.round(2))
# 4. 성능 평가
from sklearn.metrics import mean_absolute_error, mean_squared_error
mae = mean_absolute_error(test, predictions)
rmse = np.sqrt(mean_squared_error(test, predictions))
mape = np.mean(np.abs((test - predictions) / test)) * 100
print(f"\n=== 성능 지표 ===")
print(f"MAE: {mae:.2f}")
print(f"RMSE: {rmse:.2f}")
print(f"MAPE: {mape:.2f}%")
"We have three years of monthly sales data, so let's start with ARIMA. First, we check stationarity with the ADF test, and estimate p and q through ACF/PACF analysis. If seasonality is pronounced, we need to extend to SARIMA(p,d,q)(P,D,Q,12)."
"The limitations of ARIMA are the linearity assumption and the difficulty of incorporating external variables. To reflect promotion and holiday effects, you can use ARIMAX, or these days Prophet is more intuitive. However, the advantage of ARIMA is that the interpretation of its confidence intervals is statistically rigorous."
"The current ARIMA model's MAPE is 15%, but the business requirement is 10% or below. Looking at the residual analysis, there are large errors at certain points in time, which coincide with the promotion period. Let's consider adding exogenous variables or using a hybrid model."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If ARIMA is applied as is to a non-stationary time series, spurious regression (a false relationship) occurs. Be sure to verify stationarity with the ADF test, and apply differencing if necessary.
Setting the p, d, q values too high leads to overfitting. Compare models using information criteria such as AIC and BIC, and check with the Ljung-Box test whether the residuals are white noise.
ARIMA is suited to short-term forecasting. As the forecast horizon grows longer, the confidence interval widens sharply and predictive power declines. When forecasting more than 12 months ahead, use other methodologies alongside it.