Showing posts with label historical prices. Show all posts
Showing posts with label historical prices. Show all posts
Wednesday, August 15, 2012
Historical Intraday Stock Price Data with Python
By popular request, this post will present how to acquire intraday stock data from google finance using python. The general structure of the code is pretty simple to understand. First a request url is created and sent. The response is then read by python to create an array or matrix of the financial data and a vector of time data. This array is created with the help of the popular Numpy package that can be downloaded from here. Then in one if-statement, the time data is then restructured into a proper unix time format and translated to a more familiar date string for each financial data point. The translated time vector is then joined with the financial array to produce a single easy to work with financial time series array. Since Numpy has been ported to Python 3, the code I wrote should be compatibile with both Python 2.X and 3.X. Here it is:
import urllib2
import urllib
import numpy as np
from datetime import datetime
urldata = {}
urldata['q'] = ticker = 'JPM' # stock symbol
urldata['x'] = 'NYSE' # exchange symbol
urldata['i'] = '60' # interval
urldata['p'] = '1d' # number of past trading days (max has been 15d)
urldata['f'] = 'd,o,h,l,c,v' # requested data d is time, o is open, c is closing, h is high, l is low, v is volume
url_values = urllib.urlencode(urldata)
url = 'http://www.google.com/finance/getprices'
full_url = url + '?' + url_values
req = urllib2.Request(full_url)
response = urllib2.urlopen(req).readlines()
getdata = response
del getdata[0:7]
numberoflines = len(getdata)
returnMat = np.zeros((numberoflines, 5))
timeVector = []
index = 0
for line in getdata:
line = line.strip('a')
listFromLine = line.split(',')
returnMat[index,:] = listFromLine[1:6]
timeVector.append(int(listFromLine[0]))
index += 1
# convert Unix or epoch time to something more familiar
for x in timeVector:
if x > 500:
z = x
timeVector[timeVector.index(x)] = datetime.fromtimestamp(x)
else:
y = z+x*60 # multiply by interval
timeVector[timeVector.index(x)] = datetime.fromtimestamp(y)
tdata = np.array(timeVector)
time = tdata.reshape((len(tdata),1))
intradata = np.concatenate((time, returnMat), axis=1) # array of all data with the properly formated times
Subscribe to:
Posts (Atom)