In [20]:
# Joel O'Neil
#PDS - Final Project
#Experimenting with open source Yahoo Finance API 'ystockquote'
#link to ystockquote source: https://github.com/cgoldberg/ystockquote
import json
import ystockquote
import pprint
import numpy
import operator
GOOG_last = ystockquote.get_historical_prices('GOOG', '2013-11-25', '2013-11-27')
#output historical data as a dictionary of dictionaries
GOOG_last
Out[20]:
In [21]:
# Joel O'Neil
#PDS - Final Project
#Experimenting with open source Yahoo Finance API 'ystockquote'
#Modifying API to extract monthly and weekly data
import urllib
import urllib2
from urllib2 import Request, urlopen
from urllib import urlencode
def get_historical_prices(symbol, start_date, end_date):
"""
Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested dictionary (dict of dicts).
outer dict keys are dates ('YYYY-MM-DD')
"""
params = urlencode({
's': symbol,
'a': int(start_date[5:7]) - 1,
'b': int(start_date[8:10]),
'c': int(start_date[0:4]),
'd': int(end_date[5:7]) - 1,
'e': int(end_date[8:10]),
'f': int(end_date[0:4]),
'g': 'm', # <-- modifying API to extract data on a monthly basis 'm' (instead of daily)
'ignore': '.csv',
})
url = 'http://ichart.yahoo.com/table.csv?%s' % params
req = Request(url)
resp = urlopen(req)
content = str(resp.read().decode('utf-8').strip())
daily_data = content.splitlines()
#print daily_data
hist_dict = dict()
keys = daily_data[0].split(',')
#print keys
for day in daily_data[1:]:
day_data = day.split(',')
date = day_data[0]
hist_dict[date] = \
{keys[1]: day_data[1],
keys[2]: day_data[2],
keys[3]: day_data[3],
keys[4]: day_data[4],
keys[5]: day_data[5],
keys[6]: day_data[6]}
return hist_dict
hist = get_historical_prices('IBM', '2013-10-04', '2013-12-06')
hist
Out[21]:
In [29]:
# Joel O'Neil
#PDS Final Project - Stock Predictor Model
#custom function 'price_series' created to :
# 1) extract required data (Adj Close price) from the ystockquote output
# 2) plot the stock price over a given time interval
#importing necessary libraries
import json
import ystockquote #open source Yahoo Finance API
import pprint
import numpy
import operator
import numpy as np
from datetime import datetime
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
#custom function
def price_series(symbol, start_date, end_date):
series = {}
data = ystockquote.get_historical_prices(symbol, start_date, end_date)
data
for k,v in data.iteritems():
series.update({k:v['Adj Close']})
return series
##### main program block #######
#passing stock details and input
symbol = 'GOOG'
start_date = '2013-09-10'
end_date = '2013-12-06'
#calling custom function
prices = price_series(symbol, start_date, end_date)
#initializing lists to store data
date = []
price = []
dates = []
#sorting 'date' list and populating 'price' list
date = sorted(prices.keys())
n = 0
for i in date:
price.append(prices[date[n]])
n = 1 + n
#setting x-axis
dates = range(len(date))
#plotting graph
plt.plot(dates,price,color='g', label = 'GOOG stock price')
plt.xlabel('# of trading days from start date')
plt.ylabel('Price')
plt.legend(loc='upper center', bbox_to_anchor=(0.5,-0.15))
plt.show()
In [19]:
In [19]:
In [ ]: