반응형

/*********************************************************************************************************
-- Title : [Py2.7] Grid customization, colors and fills w/ Matplotlib.pyplot
-- Reference : pythonprogramming.net
-- Key word : matplotlib pyplot numpy urllib subplot2grid set_rotation set_color subplots_adjust 

                  alpha where facecolor 
*********************************************************************************************************/


-- Figure


-- Script

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
  
# -*- coding: utf-8 -*-
 
import matplotlib.pyplot as plt
import numpy as np
import urllib
import matplotlib.dates as mdates
 
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((1,1), (0,0))                                               # <-- 그래프 시작점, 개수 설정
 
    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'
 
    source_code = urllib.urlopen(stock_price_url).read()
    print source_code
 
    stock_data = []
    split_source = source_code.split('\n')
 
    for line in split_source:
        split_line = line.split(',')
        if len(split_line) == 6:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)
 
    # -- 항목별로 분리 저장(to 리스트)
    date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
                                                          delimiter=',',
                                                          unpack=True,
                                                          converters={0: bytespdate2num('%Y%m%d')})
 
    ax1.plot_date(date, closep, '-', label="Price")                                    # <-- 선그래프 출력
    ax1.plot([],[], linewidth=5, label='loss', color='r', alpha=0.5)                   # <-- 범주 추가
    ax1.plot([],[], linewidth=5, label='gain', color='g', alpha=0.5)
    #ax1.fill_between(date, closep, 15, alpha=0.3)                                     # <-- 선그래프 안에 색 채우기, alpha는 색 투명도
    #ax1.fill_between(date, closep, closep[0], alpha=0.3)                              # <-- 위와 동일함
    #ax1.fill_between(date, closep, closep[0], where=(closep > closep[0]), alpha=0.3)  # <-- 조건을 통한 색 채우기
    ax1.fill_between(date, closep, closep[0], where=(closep > closep[0]), facecolor='g', alpha=0.3)  # <-- 채우는 색 변경
    ax1.fill_between(date, closep, closep[0], where=(closep < closep[0]), facecolor='r', alpha=0.3)  # <-- 채우는 색 변경
 
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)                                                         # <-- xlabel을 45도 각도로 출력
    ax1.grid(True)                                                                     # <-- 그리드 줄 출력
    ax1.xaxis.label.set_color('c')                                                     # <-- x라벨 글자색 변경
    ax1.yaxis.label.set_color('r')
    ax1.set_yticks([0255075])                                                    # <-- y축 기준값 변경
 
                                                                                       # <-- 그래프 여백 설정
    plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
 
    plt.xlabel('xlabel:Date')
    plt.ylabel('ylabel:Price')
    plt.title('Title: STOCK')
    plt.legend()
    plt.show()
 
#graph_data('TSLA')
graph_data('EBAY')
 
 

cs

반응형

+ Recent posts