'''
Created on Mar 1, 2011

This module provides the same interface for getting data from the web or a saved file.

There is NO need to modify this file.

@author: alandavidson
@author: rcd
'''
import ystockquote


# private function, do NOT call it directly
def __processRawData (rawData, startDate, endDate):
    """
    The data that ystockquote gives us is a list of lists of strings, 
    which can be thought of as a 2D table: the outer list is a list of 
    rows, and within each row, there is an element for each column. 
    The first row are headers: strings describing what each column 
    represents. We care about columns 0 (date), 4 (price), and 5 (volume 
    traded). All other rows are for dates, though they are sorted most
    recent to least recent (chronologically backwards).

    Returns a list containing tuples of just the data we care about, 
    sorted from least recent to most recent (chronologically forwards).
    """
    # be robust regarding the parameters
    start = min(startDate, endDate)
    end = max(startDate, endDate)
    # get rid of column titles
    data = rawData[1:]
    # put in chronological order
    data.reverse()
    # return just the columns, with the proper types
    return [ (x[0], float(x[4]), int(x[5])) for x in data if start <= x[0] < end ]


def getFileData (symbol, startDate, endDate):
    '''
    The filename should specify a file with data from ystockquote. 
    Returns a list of just the data we care about (date, price, volume traded), 
    sorted chronologically.
    '''
    f = open("data/"+symbol+"_13.txt")
    data = [ line.strip().split(',') for line in f ]
    f.close()
    return __processRawData(data, startDate, endDate)


def getWebData (symbol, startDate, endDate):
    '''
    symbol is a string denoting the ticker symbol of the stock.
    start_date and end_date are strings in the form YYYYMMDD.
    Use the ystockquote library to grab historical data on a stock.
     
    Returns a list of just the data we care about (date, price, volume traded), 
    sorted chronologically.
    '''
    data = ystockquote.getHistoricalPrices(symbol, startDate, endDate)
    return __processRawData(data, startDate, endDate)
