python/주식
2. Python - Plotly 캔들 + 거래량 차트 만들기 ( 복수 차트 생성 )
맑은안개
2021. 1. 26. 05:00
들어가며..
1편에서 mplfinance, plotly 차트 라이브러리를 사용하여 캔들차트로 표현해 보았다. 본 편에서는 Plotly 라이브러리를 사용하여 일 시세 + 거래량 차트를 표현해 본다.
1편Python - 주식차트 만들기 1편, 캔들차트 만들기 ( mplfinance, Ploty )
라이브러리 설치 ( 1편에서 설치 하였다면 skip )
pip install pandas-datareader # 주식 데이터 조회
pip install plotly # 차트 라이브러리
주식 데이터 조회 ( 삼성전자 )
import plotly.graph_objects as go
import plotly.subplots as ms
import pandas_datareader as web
df = web.naver.NaverDailyReader('005930', start='20200101' , end='20201231').read()
df = df.astype(int) # Object 데이터를 int로 변환
캔들차트와 거래량을 표시할 바(Bar)차트 객체를 생성한다.
# 캔들 차트 객체 생성
candle = go.Candlestick(
x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
increasing_line_color = 'red', # 상승봉 스타일링
decreasing_line_color = 'blue' # 하락봉 스타일링
)
# 바 차트(거래량) 객체 생성
volume_bar = go.Bar(x=df.index, y=df['Volume'])
Figure 설정
fig = ms.make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.02)
두개의 행을 갖는 Figure 객체를 생성한다. shared_xaxes 함수는 Figure에 설정된 차트들의 x축을 공유하여 rangeslider를 사용하여 같이 움직이게 할 수 있다.
fig.add_trace(candle, row=1, col=1)
fig.add_trace(volume_bar, row=2, col=1)
첫번째 행에 캔들차트를 추가 하고 그 다음으로 거래량차트를 추가한다.
fig.update_layout(
title='Samsung stock price',
yaxis1_title='Stock Price',
yaxis2_title='Volume',
xaxis2_title='periods',
xaxis1_rangeslider_visible=False,
xaxis2_rangeslider_visible=True,
)
xaxis1_rangeslider_visible=False 캔들차는 rangeslider를 제거하고 xaxis2_rangeslider_visible=True 거래량 차트에 rangeslider를 셋트한다.
차트를 출력한다.
fig.show()
반응형