Skip to content

Instantly share code, notes, and snippets.

@victor-iyi
Created August 27, 2017 14:12
Show Gist options
  • Save victor-iyi/7420d1a2d17f5458c607bcf132955c28 to your computer and use it in GitHub Desktop.
Save victor-iyi/7420d1a2d17f5458c607bcf132955c28 to your computer and use it in GitHub Desktop.
Retrieve stock information for any named company's ticker
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import urllib
import numpy as np
def bytespdates2num(formt, encoding='utf-8'):
strconverter = mdates.strpdate2num(formt)
def bytesconverter(b):
s = b.decode(encoding)
return strconverter(s)
return bytesconverter
def get(stock):
try:
url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'
source_code = urllib.request.urlopen(url).read().decode()
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)
dates, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
delimiter=',',
unpack=True,
# %Y = full year 2016
# %y = half year 16
# %m = month 05
# %d = day 04
# %H = Hour
# %M = Minutes
# %S = Seconds
# 05-04-2016 ==== Today's date :)
# %m-%d-%Y
converters={0:bytespdates2num('%Y%m%d')})
return dates, closep, highp, lowp, openp, volume
except Exception as e:
return False
if __name__ == '__main__':
get('TSLA')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment