-
KT AIVLE School DX트랙 3주차-시계열 데이터KT_Aivle_School/Python 2024. 3. 24. 21:35
파이썬을 활용한 시계열 데이터 분석
시계열 데이터는 시간 순서에 따라 정렬된 데이터 포인트의 집합입니다. 이러한 데이터는 시간의 흐름에 따른 패턴, 추세, 계절성 등을 분석하는 데 유용하게 사용됩니다.
1. 시계열 데이터의 특징과 분석 방법
시계열 데이터는 일정한 시간 간격으로 수집된 데이터로, 각 데이터 포인트가 시간 순서대로 배열되어 있습니다. 이러한 데이터는 경제, 금융, 기상학 등 다양한 분야에서 발생하며, 시간의 흐름에 따른 변화를 분석하는 데 사용됩니다.
- 시계열 데이터의 특징:
- 시간 순서에 따라 배열된 데이터 포인트
- 시간 간격이 균일하거나 불규칙할 수 있음
- 시간에 따른 패턴(추세, 계절성 등)을 포함할 수 있음
- 시계열 데이터 분석 방법:
- 추세 분석: 시간의 흐름에 따른 데이터의 추세를 파악합니다.
- 시계열 데이터 분해(Decomposition): 시계열 데이터를 추세, 계절성, 잔차 등 여러 구성 요소로 분해하여 분석합니다.
- 자기상관함수(ACF): 시계열 데이터에서 현재의 값이 과거의 값과 어떤 상관관계를 가지고 있는지를 분석합니다.
1) 시간의 흐름에 따른 추세 분석: 라인차트
KOSPI 지수와 거래량 라인차트
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # KOSPI 데이터 로드 kospi = pd.read_csv('kospi.csv') plt.figure(figsize = (12,5)) # 왼쪽 축 ax1 = sns.lineplot(x = 'Date', y = 'Close', data = kospi, label = 'Close', color = 'blue', linewidth = .5) plt.legend(loc='upper left') # 오른쪽 축 생성 ax2 = ax1.twinx() sns.lineplot(x = 'Date', y = 'Volume_Lag', data = kospi, label = 'Volume', color = 'green', linewidth = .5) plt.legend(loc='upper right') plt.show()
2) 시계열 데이터 분해(Decomposition)
시각화 함수
def decomp_plot(decomp) : # 시계열 분해 결과를 받아서 데이터프레임으로 저장 result = pd.DataFrame({'observed':decomp.observed, 'trend':decomp.trend, 'seasonal':decomp.seasonal, 'residual':decomp.resid}) # 4개의 그래프로 나눠서 그리기 plt.subplot(4,1,1) plt.plot(result['observed']) plt.ylabel('observed') plt.subplot(4,1,2) plt.plot(result['trend']) plt.ylabel('trend') plt.subplot(4,1,3) plt.plot(result['seasonal']) plt.ylabel('seasonal') plt.subplot(4,1,4) plt.plot(result['residual']) plt.ylabel('residual') plt.show() return result
시계열 데이터 분해
# 시계열 데이터 일단위 분해 decomp = sm.tsa.seasonal_decompose(bike['Count'], model = 'additive', period = 24) # 그래프 그리기 plt.figure(figsize=(12, 8)) result = decomp_plot(decomp)
# 시계열 데이터 주단위 분해 decomp = sm.tsa.seasonal_decompose(bike['Count'], model = 'additive', period = 24 * 7) # 그래프 그리기 plt.figure(figsize=(12, 8)) result = decomp_plot(decomp)
3) 자기상관함수(ACF)
자기상관함수를 활용한 시계열 데이터 분석 예시 코드입니다.
# 반복문으로 시차를 늘려가면서 데이터셋 만들기 temp = bike[['Count']].copy() for i in range(1,21) : var = 'lag' + str(i) temp[var] = temp['Count'].shift(i) temp.head(20)
# 각 시차간의 상관계수 temp.corr()
plot_acf(bike['Count'], lags = 60) plt.grid() plt.show()
'KT_Aivle_School > Python' 카테고리의 다른 글
KT AIVLE School DX트랙 5주차-데이터 분석표현 (1) 2024.04.19 KT AIVLE School DX트랙 4주차-웹크롤링 (0) 2024.03.24 KT AIVLE School DX트랙 3주차-이변량 분석 2 (0) 2024.03.24 KT AIVLE School DX트랙 3주차-이변량 분석 (1) 2024.03.24 KT AIVLE School DX트랙 3주차-단변량 분석 (0) 2024.03.24 - 시계열 데이터의 특징: