반응형
/*******************************************************************************************************************
-- Title : [Py3.5] More Indicator data w/ Matplotlib.pyplot
-- Reference : pythionprogramming.net
-- Key word : pythion 파이썬 matplotlib pyplot candlestick candlestick_ohlc numpy subplot subplot2grid
set_major_formatter set_major_locator annotate dict annotate() dict() 촛대 차트 촛대 그래프
주석 패널 indicator
*******************************************************************************************************************/
-- Figure
-- Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mticker from matplotlib.finance import candlestick_ohlc from matplotlib import style import numpy as np import urllib import datetime as dt # -- 차트 스타일 설정 style.use('fivethirtyeight') print(plt.style.available) # -- 차트 스타일 관련 파일 경로 출력(?) print(plt.__file__) MA1 = 10 MA2 = 30 def moving_average(values, window): weights = np.repeat(1.0, window) / window smas = np.convolve(values, weights, 'valid') return smas def high_minus_low(highs, lows): return highs - lows # -- 일자 변환 처리 def bytespdate2num(fmt, encoding='utf-8'): strconverter = mdates.strpdate2num(fmt) def bytesconverter(b): s = b.decode(encoding) return strconverter(s) return bytesconverter # -- 차트 생성 위한 데이터 처리 및 출력(Subplot 설정, 표의 셀 합치기와 유사) def graph_data(stock): fig = plt.figure() ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=1, colspan=1) plt.title(stock) ax2 = plt.subplot2grid((6, 1), (1, 0), rowspan=4, colspan=1) plt.xlabel('Date') plt.ylabel('Price') ax3 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1) # -- URL 경로 변수 stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=1y/csv' # print(stock_price_url) # -- URL 통해 데이터소스 가져오기 source_code = urllib.request.urlopen(stock_price_url).read().decode() # print (source_code) # -- '\n' 기준으로 분리하여 리스트로 변환 stock_data = [] split_source = source_code.split('\n') # print (split_source) # -- 콤마(,)를 기준으로 분리 for line in split_source: split_line = line.split(',') # print (split_line) # -- 리스트가 6개이고 label:value형태 아닌것만 추출 if len(split_line) == 6: if 'values' not in line and 'labels' not in line: stock_data.append(line) # print (stock_data) # print (stock_data) # print ("-" * 100) # -- URL 통해 데이터소스 가져오기 date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data, delimiter=',', unpack=True, converters={0: bytespdate2num('%Y%m%d')}) # print(date) # print(closep) # print(len(date)) x = 0 y = len(date) ohlc = [] # -- numpy를 tuple로 저장 while x < y: append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x] ohlc.append(append_me) x += 1 # -- 이동 평균과 마이너스 계산 ma1 = moving_average(closep, MA1) ma2 = moving_average(closep, MA2) start = len(date[MA2 - 1:]) h_l = list(map(high_minus_low, highp, lowp)) # -- high-low 설정 ax1.plot_date(date, h_l, '-') # -- 촛대차트 정의 candlestick_ohlc(ax2, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f') # plt.show() # -- X축 값의 45도 회전 for label in ax2.xaxis.get_ticklabels(): label.set_rotation(45) # plt.show() # -- X축 값 일자 표현 ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ax2.xaxis.set_major_locator(mticker.MaxNLocator(10)) ax2.grid(True) # -- Annotating Last Price Stock Chart bbox_props = dict(boxstyle='round', fc='w', ec='k', lw=1) ax2.annotate(str(closep[-1]), (date[-1], closep[-1]), xytext=(date[-1] + 4, closep[-1]), bbox=bbox_props) # plt.show() ## # Annotation example with arrow ## ax2.annotate('Bad News!',(date[11],highp[11]), ## xytext=(0.8, 0.9), textcoords='axes fraction', ## arrowprops = dict(facecolor='grey',color='grey')) ## ## ## # Font dict example ## font_dict = {'family':'serif', ## 'color':'darkred', ## 'size':15} ## # Hard coded text ## ax2.text(date[10], closep[1],'Text Example', fontdict=font_dict) # -- ax3에 이동 평균 추가 ax3.plot(date[-start:], ma1[-start:]) ax3.plot(date[-start:], ma2[-start:]) # -- 차트 설정 # plt.legend() plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0) plt.show() graph_data('EBAY') | cs |
-- Description of Figure 2,3
* https://www.pythonprogramming.net/share-x-axis-sharex-matplotlib-tutorial/?completed=/fill-pruning-matplotlib-tutorial/
* https://www.pythonprogramming.net/multi-y-axis-twinx-matplotlib-tutorial/?completed=/share-x-axis-sharex-matplotlib-tutorial/
* https://www.pythonprogramming.net/share-x-axis-sharex-matplotlib-tutorial/?completed=/fill-pruning-matplotlib-tutorial/
* https://www.pythonprogramming.net/multi-y-axis-twinx-matplotlib-tutorial/?completed=/share-x-axis-sharex-matplotlib-tutorial/
반응형