Download Stock Prices

Goal: Download stock price data

Data source: Yahoo Finance

The program recipe below is written in python.

Import necessary libraries. If requests modules is not already present, install that package using: "pip install requests"

import requests, csv

from datetime import datetime

Determine the download url.

def get_link(symbol, start, end =

download_url = "{0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}&g=d&ignore=.csv"

if type(start) is str:

start = datetime.strptime(start, "%Y-%m-%d")

if type(end) is str:

end = datetime.strptime(end, "%Y-%m-%d")

return download_url.format(symbol,, start.month, start.year,, end.month, end.year)

Load stock symbols. I already save the stock symbols in a csv file. The file is attached below. Update the location of the file in the code below.

with open("/data/S&P500/S&P500.csv") as f:

csv_reader = csv.reader(f)

stocks = [r for r in csv_reader][1:]

symbols = [stock[0] for stock in stocks]

Download stock prices for each of S&P500 stocks since the Jan 01, 2016. Update the directory where you want to store the csv files.

errors = []

for i, symbol in enumerate(symbols):

link = get_link(symbol, "2016-01-01")

res = requests.get(link)

print(i, symbol, link, res.status_code)

if res.status_code == 200:

output_file_name = "/data/S&P500/prices/{0}.csv".format(symbol)

with open(output_file_name, "w") as f:




print("Errors", errors)