Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

Is there a way to automatically download historical prices of stocks from yahoo finance or google finance (csv format)? Preferably in Python.

1 Answer

0 votes
by (108k points)

You can refer the following code to pull all the historical data on a particular company. The code pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your list of ticker symbols that you want to pull.

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="

def make_url(ticker_symbol):

    return base_url + ticker_symbol

Output_p = "C:/path/to/output/directory"

def make_filename(ticker_symbol, directory="S&P"):

    return Output_p + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):

    try:

        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))

    except urllib.ContentTooShortError as e:

        outfile = open(make_filename(ticker_symbol, directory), "w")

        outfile.write(e.content)

        outfile.close()

If you are interested in learning Python and want to become a certified Python expert, then check out Python Courses and upskill yourself.

Browse Categories

...