시계열 데이터의 사용자 정의 틱 포맷터

Beginner

This tutorial is from open-source community. Access the source code

소개

금융 시계열과 같은 일일 데이터를 플로팅할 때, 주말과 같이 데이터가 없는 날짜는 종종 제외하고 싶어집니다. 이렇게 하면 데이터가 없는 날짜에 대한 추가 공간 없이 데이터를 정기적인 간격으로 플로팅할 수 있습니다. 이 랩에서는 원하는 플롯을 얻기 위해 '인덱스 포매터 (index formatter)'를 사용하는 방법을 배웁니다.

VM 팁

VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접속하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수도 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.

학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.

필요한 라이브러리 및 데이터 가져오기

먼저 필요한 라이브러리인 matplotlib, numpy, matplotlib.cbook을 가져와야 합니다. 또한 mpl-data/sample_data 디렉토리에서 date, open, high, low, close, volume, adj_close 필드를 가진 yahoo csv 데이터로부터 numpy record array 를 로드해야 합니다. record array 는 날짜 열에서 일 단위 ('D') 로 np.datetime64 로 날짜를 저장합니다. 이 데이터를 사용하여 금융 시계열을 플로팅합니다.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook

## Load data from sample_data directory
r = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)
r = r[:9]  ## get the first 9 days

주말에 기본 간격으로 데이터 플로팅

먼저 matplotlib 의 plot 함수를 사용하여 주말에 기본 간격으로 데이터를 플로팅합니다. 또한 흰색 점선으로 일일 데이터의 간격을 강조 표시합니다.

## Plot data with gaps on weekends
fig, ax1 = plt.subplots(figsize=(6, 3))
ax1.plot(r.date, r.adj_close, 'o-')

## Highlight gaps in daily data
gaps = np.flatnonzero(np.diff(r.date) > np.timedelta64(1, 'D'))
for gap in r[['date', 'adj_close']][np.stack((gaps, gaps + 1)).T]:
    ax1.plot(gap.date, gap.adj_close, 'w--', lw=2)
ax1.legend(handles=[ml.Line2D([], [], ls='--', label='Gaps in daily data')])

ax1.set_title("Plotting Data with Default Gaps on Weekends")
ax1.xaxis.set_major_locator(DayLocator())
ax1.xaxis.set_major_formatter(DateFormatter('%a'))

사용자 정의 인덱스 포맷터 생성

0, 1, ... len(data) 에서 시작하는 인덱스에 대해 데이터를 플로팅하기 위해 사용자 정의 인덱스 포맷터를 생성합니다. 이 포맷터는 눈금 표시를 정수가 아닌 시간으로 형식화합니다.

## Create custom index formatter
fig, ax2 = plt.subplots(figsize=(6, 3))
ax2.plot(r.adj_close, 'o-')

## Format x-axis as times
def format_date(x, _):
    try:
        ## convert datetime64 to datetime, and use datetime's strftime:
        return r.date[round(x)].item().strftime('%a')
    except IndexError:
        pass

ax2.set_title("Creating Custom Index Formatter")
ax2.xaxis.set_major_formatter(format_date)  ## internally creates FuncFormatter

포맷터에 콜러블 (Callable) 사용

.Axis.set_major_formatter에 함수를 전달하는 대신, __call__을 구현하는 클래스의 인스턴스와 같은 다른 콜러블을 사용할 수 있습니다. 이 단계에서는 눈금 표시를 시간으로 형식화하는 MyFormatter 클래스를 생성합니다.

## Use a callable for formatter
class MyFormatter(Formatter):
    def __init__(self, dates, fmt='%a'):
        self.dates = dates
        self.fmt = fmt

    def __call__(self, x, pos=0):
        """Return the label for time x at position pos."""
        try:
            return self.dates[round(x)].item().strftime(self.fmt)
        except IndexError:
            pass

ax2.xaxis.set_major_formatter(MyFormatter(r.date, '%a'))

플롯 표시

이제 matplotlib 의 show 함수를 사용하여 플롯을 표시합니다.

plt.show()

요약

이 랩에서는 주말 간격 없이 금융 시계열을 플롯하기 위해 사용자 정의 인덱스 포맷터 (custom index formatter) 를 사용하는 방법을 배웠습니다. 또한 함수 대신 포맷터에 콜러블 (callable) 을 사용하는 방법도 배웠습니다. 이러한 기술을 사용하여 일별 데이터의 시각적으로 더 매력적인 플롯을 만들 수 있습니다.