How to mine stock values history from Google using Python

By using pandas_datareader.data you can easily extract from the web any stock history value. The following example is a function that will save a CVS file of the stock values from the input sock name.

##################################################################################
# Downloads data and save it as CSV
# To get fundamentals you would have to pay
# https://www.reddit.com/r/algotrading/comments/4byj5k/is_there_a_python_script_to_get_historical/
##################################################################################
def getWebData(stockName, dataDates):
    import pandas_datareader.data as web

    #refresh files only if they haven't done within the day
    filePath = "../data/" + stockName + '.csv'
    
    #refresh data ones a day
    todayDate = dataDates[1]

    #if file exist, get files modification data. Else stamp old date
    if (path.exists(filePath)):
        fileDate = datetime.fromtimestamp(path.getmtime(filePath)).date()
    else:
        fileDate = datetime.now().date() - timedelta(days=1)
        
    if todayDate > fileDate:
        
        # Define which on-line source one should use
        data_source = 'google'

        # We would like all available data from dataDates[0] until dataDates[1]
        start_date = dataDates[0]
        end_date = todayDate

        # User pandas_reader.data.DataReader to load the desired data. As simple as that.
        try:
            panel_data = web.DataReader(stockName, data_source, start_date, end_date)
            panel_data.to_csv(filePath)
        except:
            print(stockName, "was not found")
            return (0)
               
    return (filePath

 

Manuel Cuevas

Manuel Cuevas

Hello, I'm Manuel Cuevas a Software Engineer with background in machine learning and artificial intelligence.

Recent post