반응형

/*******************************************************************************************************************
-- Title : [Py3.5] Annotating(주석) Last Price Stock Chart w/ Matplotlib.pyplot
-- Reference : pythionprogramming.net
-- Key word : 주석 annotation matplotlib pyplot candlestick candlestick_ohlc numpy np.loadtext dict() dict
                  annotate annotate() pythion 파이썬 촛대 차트 촛대 그래프
*******************************************************************************************************************/

-- 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
 
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__)
 
# -- 일자 변환 처리
def bytespdate2num(fmt, encoding='utf-8'):
    strconverter = mdates.strpdate2num(fmt)
 
    def bytesconverter(b):
        s = b.decode(encoding)
        return strconverter(s)
 
    return bytesconverter
 
# -- 차트 생성위한 데이터 처리 및 출력
def graph_data(stock):
    fig = plt.figure()
    ax1 = plt.subplot2grid((11), (00))
 
    # -- URL 경로 변수
    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=1m/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:                                          # list개수가 6개이면
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)
                #print (stock_data)
 
    #print (stock_data)
    #print ("-" * 100)
 
    # -- 리스트에 있는 항목을 np.loadtxt로 구분하여 저장
    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                                              # <class 'tuple'>
 
    # -- 촛대차트 정의
    candlestick_ohlc(ax1, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
    #plt.show()                                                           # Figure-1
 
    # -- X축 값의 45도 회전
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)
    #plt.show()                                                           # Figure-2
 
    # -- X축 값 일자 표현
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    #plt.show()                                                           # Figure-3
 
    # -- Annotating Last Price Stock Chart
    bbox_props = dict(boxstyle='round', fc='w', ec='k', lw=1)
 
    ax1.annotate(str(closep[-1]), (date[-1], closep[-1]),
                 xytext=(date[-1+ 3, closep[-1]), bbox=bbox_props)
    #plt.show()                                                           # Figure-4 
 
    # -- 차트 설정
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title(stock)
    # plt.legend()
    plt.subplots_adjust(left=0.11, bottom=0.24, right=0.87, top=0.90, wspace=0.2, hspace=0)
    plt.show()                                                            # Figure-5
 
 
graph_data('EBAY')
 

cs

반응형

+ Recent posts