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]:
{'2013-11-25': {'Adj Close': '1045.93',
  'Close': '1045.93',
  'High': '1053.19',
  'Low': '1035.02',
  'Open': '1037.16',
  'Volume': '1613000'},
 '2013-11-26': {'Adj Close': '1058.41',
  'Close': '1058.41',
  'High': '1061.50',
  'Low': '1042.94',
  'Open': '1048.60',
  'Volume': '2286300'},
 '2013-11-27': {'Adj Close': '1063.11',
  'Close': '1063.11',
  'High': '1068.00',
  'Low': '1060.00',
  'Open': '1062.03',
  'Volume': '1123600'}}

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]:
{'2013-10-04': {'Adj Close': '178.25',
  'Close': '179.21',
  'High': '186.99',
  'Low': '172.57',
  'Open': '184.17',
  'Volume': '6288700'},
 '2013-11-01': {'Adj Close': '179.68',
  'Close': '179.68',
  'High': '186.24',
  'Low': '177.31',
  'Open': '179.81',
  'Volume': '5192700'},
 '2013-12-02': {'Adj Close': '177.67',
  'Close': '177.67',
  'High': '179.59',
  'Low': '175.16',
  'Open': '179.46',
  'Volume': '5911100'}}

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 [ ]: