본문 바로가기
Python 과 머신러닝/II. 데이터처리 문법

[Python 머신러닝] 2장. 차트 시각화 - (3)시계열 데이터

by JoyfulS 2019. 10. 18.

3. 시계열 데이터 시각화

"""
 1. 날짜형식 수정
 2. 시계열 시각화
 3. 이동평균 기능 -> 시각화
"""

from datetime import datetime   # 패키지 - 모듈 (이름 같음)
import pandas as pd   # csv file read
import matplotlib.pyplot as plt   # 시계열 시각화


# 1. 날짜형식 수정

# ex) 8-2-2019 -> 2019-08-02

cospi.csv
0.01MB

cospi = pd.read_csv("../data/cospi.csv")
cospi.info()
'''
RangeIndex: 247 entries, 0 to 246
Data columns (total 6 columns):
'''
cospi.head()
cospi.tail()

cospi.head( )와 cospi.tail( )의 출력 결과

# 미국식 날짜 -> 한국식 날짜

sdate = '26-Feb-16'
datetime.strptime(sdate, '%d-%b-%y')   # (2016, 2, 26, 0, 0)

date = cospi['Date']
len(date) # 247

# list 내포
kdate = [ datetime.strptime(d, '%d-%b-%y') for d in date ]
kdate

# 날짜 형식 변경
cospi['Date'] = kdate
cospi


# 2. 시계열 시각화


# 1개 칼럼으로 추세 그래프
cospi['High'].plot(title = 'Trend line of High column')


# index 수정

# 형식 ) data.set_index('인덱스로 사용할 칼럼')

 

cospi.index # 행 이름 : RangeIndex(start=0, stop=247, step=1)
cospi.head()

index 수정 전 : index는 0, 1, 2, 3, ...

# 특정 칼럼 -> index 지정
new_cospi = cospi.set_index('Date')
new_cospi.head()

index 수정 후 : index는 날짜데이터

# 날짜데이터를 index로 사용하면 연단위, 월단위, 일단위 검색 가능

new_cospi['2016']
new_cospi['2015']
new_cospi['2016-02']
new_cospi['2016-02':'2016-01']
new_cospi['2016-02-10':'2016-02-01']


# subset 생성
new_cospi_HL = new_cospi[['High', 'Low']]
new_cospi_HL.head()

 

# 년도 기준
new_cospi_HL['2016'].plot(title = 'High vs Low 2016 year')


# 월 기준
new_cospi_HL['2016-01'].plot(title = 'High vs Low 2016 year 1 month')

# 3. 이동평균 기능 -> 시각화

# 평활 : 지정한 날짜 단위 평균 -> 이동 roll_mean5 = pd.Series.rolling(new_cospi_HL['High'], window=5, center = False).mean()
roll_mean10 = pd.Series.rolling(new_cospi_HL['High'], window=10, center = False).mean()
roll_mean20 = pd.Series.rolling(new_cospi_HL['High'], window=20, center = False).mean()

# window는 단위 - 5일 단위, 10일 단위, 20일 단위

# High 칼럼 추세 그래프
new_cospi_HL['High'].plot(color='blue', label='High Column')

# roll mean 추세 그래프
roll_mean5.plot(color='red', label='5 day rolling mean')
roll_mean10.plot(color='orange', label='10 day rolling mean')
roll_mean20.plot(color='pink', label='20 day rolling mean')


# subplot 적용
fig = plt.figure(figsize = (12, 4))
chart = fig.add_subplot(1,1,1)

chart.plot(new_cospi_HL['High'], color='blue' , label='High Column')
chart.plot(roll_mean5, color='red' , label='5 day rolling mean')
chart.plot(roll_mean10, color='orange' , label='10 day rolling mean')
chart.plot(roll_mean20, color='pink' , label='20 day rolling mean')
plt.legend(loc = 'best')

댓글