반응형
/*********************************************************************************************************
-- Title : [Py2.7] Data(.csv) from Internet w/ Matplotlib.pyplot
-- Reference : pythonprogramming.net
-- Key word : matplotlib pyplot numpy urllib csv urlopen split
*********************************************************************************************************/
-- 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 70 71 72 73 | # -*- 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): # http://chartapi.finance.yahoo.com/instrument/1.0/TSLA/chartdata;type=quote;range=10y/csv stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv' # # ---------------------------------------- # # -- urllib.uropen 테스트 # # ---------------------------------------- # f = urllib.urlopen(stock_price_url) # # print f.headers # 헤더출력 # print '-'*300 # print f.code # print '-'*300 # print f.read() # 실제 소스 출력 source_code = urllib.urlopen(stock_price_url).read() #print source_code stock_data = [] split_source = source_code.split('\n') # 줄단위를 리스트로 변경 #print split_source 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) # 리스트에 추가 #print stock_data # -- 항목별로 분리 저장(to 리스트) date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data, delimiter=',', unpack=True, # %Y = full year. 2015 # %y = partial year 15 # %m = number month # %d = number day # %H = hours # %M = minutes # %S = seconds # 12-06-2014 # %m-%d-%Y converters={0: bytespdate2num('%Y%m%d')}) plt.plot_date(date, closep, '-', label="Price") plt.xlabel('xlabel') plt.ylabel('ylabel') plt.title('Title: Data from the INternet for Matplotlib') plt.legend() plt.show() graph_data('TSLA') | cs |
반응형