반응형

/*******************************************************************************************************************
-- Title : [Py2.7] Candlestick OHLC graphs(촛대 그래프) w/ Matplotlib.pyplot
-- Reference : pythonprogramming.net
-- Key word : python 파이썬 matplotlib pyplot finance candlestick ohlc numpy ticker dates urllib datetime
                  촛대 차트 촛대 그래프
*******************************************************************************************************************/


-- Chart



-- 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
# -*- coding: utf-8 -*-
 
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from matplotlib.finance import candlestick_ohlc
 
import numpy as np
import urllib
import datetime as dt
 
 
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))
 
    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.urlopen(stock_price_url).read()
    #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
 
        if len(split_line) == 6:
            if 'values' not in line and 'labels' not in line:             # labels:values 형태이면 SKIP
                stock_data.append(line)
    #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 type(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
 
    print type(append_me)
 
    candlestick_ohlc(ax1, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
 
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)
 
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.grid(True)
 
    plt.xlabel('xlabel:Date')
    plt.ylabel('ylabel:Price')
    plt.title(stock)
    plt.legend()                                                          # warning이유 모르겠다!
    plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
    plt.show()
 
 
graph_data('EBAY')
 

cs

반응형

+ Recent posts