시계열 분석은 주어진 데이터를 기반으로 미래의 값을 예측하는데 유용한 방법입니다. 파이썬에서 이를 수행하기 위해 주로 `pandas`, `matplotlib`, `statsmodels`와 같은 라이브러리를 사용합니다. 주어진 데이터를 이용하여 2024년도 1~6월까지의 매출량을 예측하는 과정을 단계별로 설명드리겠습니다.
### 1. 데이터 전처리
먼저, 데이터를 pandas DataFrame으로 변환하고, 날짜 형식으로 처리합니다.
```python
import pandas as pd
# 데이터 생성
data = {
'date': ['21/01', '21/02', '21/03', '21/04', '21/05', '21/06', '21/07', '21/08', '21/09', '21/10', '21/11', '21/12',
'22/01', '22/02', '22/03', '22/04', '22/05', '22/06', '22/07', '22/08', '22/09', '22/10', '22/11', '22/12',
'23/01', '23/02', '23/03', '23/04', '23/05', '23/06', '23/07', '23/08', '23/09', '23/10', '23/11', '23/12'],
'sales': [8830, 5748, 9229, 6941, 6972, 6292, 9255, 6560, 6221, 7397, 9334, 8816,
8900, 6700, 9100, 6900, 7000, 6400, 9200, 6500, 6200, 7500, 9300, 8800,
8700, 6900, 9000, 6800, 7100, 6600, 9100, 6600, 6300, 7400, 9200, 8900],
'big_cf': ['면류라면류'] * 36 # 컬럼 big_cf는 분석에 사용되지 않음
}
# DataFrame 생성
df = pd.DataFrame(data)
# 날짜 형식 변환 (연-월)
df['date'] = pd.to_datetime(df['date'], format='%y/%m')
# date 컬럼을 인덱스로 설정
df.set_index('date', inplace=True)
# 데이터 확인
print(df.head())
```
### 2. 시계열 데이터 시각화
먼저 데이터를 시각화하여 추세를 파악합니다.
```python
import matplotlib.pyplot as plt
# 시계열 데이터 시각화
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['sales'], marker='o')
plt.title('Monthly Sales Data')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.grid(True)
plt.show()
```
### 3. 시계열 분해 (추세, 계절성, 불규칙성 확인)
시계열 데이터를 추세(trend), 계절성(seasonality), 잔차(residuals)로 분해할 수 있습니다.
```python
from statsmodels.tsa.seasonal import seasonal_decompose
# 시계열 분해 (연간 주기)
decomposition = seasonal_decompose(df['sales'], model='additive', period=12)
# 시각화
decomposition.plot()
plt.show()
```
### 4. 모델 생성 및 데이터 분할
`ARIMA`(AutoRegressive Integrated Moving Average) 모델을 사용하여 예측합니다. 24개월의 데이터를 학습용으로 사용하고 이후를 예측합니다.
```python
from statsmodels.tsa.arima.model import ARIMA
# ARIMA 모델 생성 (p, d, q 파라미터는 추정이 필요)
model = ARIMA(df['sales'], order=(1, 1, 1))
# 모델 학습
model_fit = model.fit()
# 모델 요약 출력
print(model_fit.summary())
```
### 5. 예측 수행
24년 1월부터 6월까지의 매출량을 예측합니다.
```python
# 6개월 예측 (2024년 1월 ~ 6월)
forecast = model_fit.forecast(steps=6)
# 예측 결과 출력
print(forecast)
```
### 6. 예측 시각화
예측 결과를 기존 데이터와 함께 시각화합니다.
```python
# 예측 기간 생성
forecast_index = pd.date_range(start='2024-01-01', periods=6, freq='M')
# 예측 결과를 시리즈로 변환
forecast_series = pd.Series(forecast, index=forecast_index)
# 기존 데이터와 예측 데이터 함께 시각화
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['sales'], label='Observed', marker='o')
plt.plot(forecast_series.index, forecast_series, label='Forecast', marker='o', color='red')
plt.title('Sales Forecast (2024 Jan - Jun)')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.grid(True)
plt.show()
```
### 7. 결과 요약
- 데이터는 먼저 pandas로 처리하여 `date`를 인덱스로 설정하였고, 시계열 데이터를 시각화하여 트렌드를 확인했습니다.
- `seasonal_decompose`를 통해 데이터의 계절성과 추세를 분리해 확인한 뒤, `ARIMA` 모델을 사용해 예측을 수행했습니다.
- 2024년 1월부터 6월까지의 매출량을 예측하고 시각화하였습니다.
이러한 과정으로 시계열 분석을 통해 예측을 할 수 있습니다.