pandas 롤링 윈도우 함수

Python으로 시계열 데이터 다루기

Stefan Jansen

Founder & Lead Data Scientist at Applied Artificial Intelligence

pandas의 윈도우 함수

  • 윈도우는 시계열의 하위 구간을 나타냅니다
  • 윈도우 내 하위 구간의 지표를 계산합니다
  • 지표로 구성된 새로운 시계열을 생성합니다
  • 윈도우 유형 두 가지:
    • 롤링: 크기 고정, 슬라이딩 방식 (이번 강의)
    • 확장: 이전 값 전체 포함 (다음 강의)
Python으로 시계열 데이터 다루기

롤링 평균 계산

data = pd.read_csv('google.csv', parse_dates=['date'], index_col='date')
DatetimeIndex: 1761 entries, 2010-01-04 to 2016-12-30
Data columns (total 1 columns):
price     1761 non-null float64
dtypes: float64(1)

ch3_1_v2 - Rolling Window Functions with Pandas.010.png

Python으로 시계열 데이터 다루기

롤링 평균 계산

# Integer-based window size
data.rolling(window=30).mean() # fixed # observations
DatetimeIndex: 1761 entries, 2010-01-04 to 2017-05-24
Data columns (total 1 columns):
price    1732 non-null float64
dtypes: float64(1)
  • window=30: 영업일 수
  • min_periods: 30 미만 값 설정 시 초기 일자의 결과도 반환
Python으로 시계열 데이터 다루기

롤링 평균 계산

# Offset-based window size
data.rolling(window='30D').mean() # fixed period length
DatetimeIndex: 1761 entries, 2010-01-04 to 2017-05-24
Data columns (total 1 columns):
price    1761 non-null float64
dtypes: float64(1)
  • 30D: 달력 기준 일수
Python으로 시계열 데이터 다루기

90일 롤링 평균

r90 = data.rolling(window='90D').mean()

google.join(r90.add_suffix('_mean_90')).plot()

ch3_1_v2 - Rolling Window Functions with Pandas.017.png

Python으로 시계열 데이터 다루기

90일 & 360일 롤링 평균

data['mean90'] = r90

r360 = data['price'].rolling(window='360D'.mean()
data['mean360'] = r360; data.plot()

ch3_1_v2 - Rolling Window Functions with Pandas.020.png

Python으로 시계열 데이터 다루기

다중 롤링 지표 (1)

r = data.price.rolling('90D').agg(['mean', 'std'])

r.plot(subplots = True)

ch3_1_v2 - Rolling Window Functions with Pandas.022.png

Python으로 시계열 데이터 다루기

다중 롤링 지표 (2)

rolling = data.google.rolling('360D')

q10 = rolling.quantile(0.1).to_frame('q10')
median = rolling.median().to_frame('median')
q90 = rolling.quantile(0.9).to_frame('q90')
pd.concat([q10, median, q90], axis=1).plot()

ch3_1_v2 - Rolling Window Functions with Pandas.024.png

Python으로 시계열 데이터 다루기

연습해 봅시다!

Python으로 시계열 데이터 다루기

Preparing Video For Download...