맞춤형 주가 그래프 생성

Beginner

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

소개

이 랩에서는 Matplotlib 을 사용하여 플롯 프레임, 눈금선, 눈금 레이블 및 선 그래프 속성의 사용자 정의 스타일을 시연하는 여러 시계열 그래프를 만드는 방법을 배우게 됩니다. 이 그래프는 32 년 동안 다양한 회사의 주가를 표시합니다.

VM 팁

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

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

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

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

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.cbook import get_sample_data
import matplotlib.transforms as mtransforms

주식 데이터 로드

with get_sample_data('Stocks.csv') as file:
    stock_data = np.genfromtxt(
        file, delimiter=',', names=True, dtype=None,
        converters={0: lambda x: np.datetime64(x, 'D')}, skip_header=1)

Figure 및 Axis 객체 생성

fig, ax = plt.subplots(1, 1, figsize=(6, 8), layout='constrained')

플롯에 사용할 색상 정의

ax.set_prop_cycle(color=[
    '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
    '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
    '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
    '#17becf', '#9edae5'])

플롯할 주식의 이름 및 티커 설정

stocks_name = ['IBM', 'Apple', 'Microsoft', 'Xerox', 'Amazon', 'Dell',
               'Alphabet', 'Adobe', 'S&P 500', 'NASDAQ']
stocks_ticker = ['IBM', 'AAPL', 'MSFT', 'XRX', 'AMZN', 'DELL', 'GOOGL',
                 'ADBE', 'GSPC', 'IXIC']

겹침을 방지하기 위해 레이블 위치를 수직으로 수동 조정

y_offsets = {k: 0 for k in stocks_ticker}
y_offsets['IBM'] = 5
y_offsets['AAPL'] = -5
y_offsets['AMZN'] = -6

각 주식을 고유한 색상으로 개별 플롯

for nn, column in enumerate(stocks_ticker):
    ## Plot each line separately with its own color.
    ## don't include any data with NaN.
    good = np.nonzero(np.isfinite(stock_data[column]))
    line, = ax.plot(stock_data['Date'][good], stock_data[column][good], lw=2.5)

    ## Add a text label to the right end of every line. Most of the code below
    ## is adding specific offsets y position because some labels overlapped.
    y_pos = stock_data[column][-1]

    ## Use an offset transform, in points, for any text that needs to be nudged
    ## up or down.
    offset = y_offsets[column] / 72
    trans = mtransforms.ScaledTranslation(0, offset, fig.dpi_scale_trans)
    trans = ax.transData + trans

    ## Again, make sure that all labels are large enough to be easily read
    ## by the viewer.
    ax.text(np.datetime64('2022-10-01'), y_pos, stocks_name[nn],
            color=line.get_color(), transform=trans)

x 축 및 y 축의 제한 설정, 제목 및 그리드 추가

ax.set_xlim(np.datetime64('1989-06-01'), np.datetime64('2023-01-01'))
fig.suptitle("Technology company stocks prices dollars (1990-2022)", ha="center")
ax.spines[:].set_visible(False)
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
ax.set_yscale('log')
ax.grid(True, 'major', 'both', ls='--', lw=.5, c='k', alpha=.3)
ax.tick_params(axis='both', which='both', labelsize='large',
               bottom=False, top=False, labelbottom=True,
               left=False, right=False, labelleft=True)

그래프 표시

plt.show()

요약

이 랩에서는 Matplotlib 을 사용하여 플롯 프레임, 눈금선, 눈금 레이블 및 선 그래프 속성의 사용자 정의 스타일을 보여주는 여러 시계열 그래프를 만드는 방법을 배웠습니다. 또한 각 주식을 고유한 색상으로 개별적으로 플롯하고, x 축 및 y 축의 제한을 설정하고, 제목과 그리드를 추가하는 방법을 배웠습니다.