Last active
April 21, 2018 08:27
-
-
Save lucaslouca/230dc00b30c03609b44bd46b29117c84 to your computer and use it in GitHub Desktop.
Fetches 10-Year Historical Stock Prices from Nasdaq and saves them as CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| import bs4 as bs | |
| import csv | |
| import re | |
| def historical_prices(symbol:str): | |
| url = "https://www.nasdaq.com/symbol/{0}/historical".format(symbol) | |
| headers = {'content-type' : 'application/json'} | |
| data = "10y|false|{0}".format(symbol) | |
| resp = requests.post(url, data=data, headers=headers) | |
| soup = bs.BeautifulSoup(resp.text, 'lxml') | |
| historical_container = soup.find("div", {"id" : "quotes_content_left_pnlAJAX"}) | |
| table = historical_container.find("table") | |
| historical_prices = [] | |
| for row in table.findAll('tr')[2:]: | |
| date = re.sub(r"[\n\t\s]*", "", row.findAll('td')[0].text) | |
| price_open = re.sub(r"[\n\t\s]*", "", row.findAll('td')[1].text) | |
| price_high = re.sub(r"[\n\t\s]*", "", row.findAll('td')[2].text) | |
| price_low = re.sub(r"[\n\t\s]*", "", row.findAll('td')[3].text) | |
| price_close = re.sub(r"[\n\t\s]*", "", row.findAll('td')[4].text) | |
| volume = re.sub(r"[\n\t\s]*", "", row.findAll('td')[5].text) | |
| historical_prices.append((date,price_open,price_high,price_low,price_close,volume)) | |
| # Save to CSV | |
| file_name = "{0}_10y.csv".format(symbol) | |
| with open(file_name, 'w') as csv_file: | |
| writer = csv.writer(csv_file) | |
| writer.writerow(['date', 'open', 'high', 'low', 'close', 'volume']) | |
| for row in historical_prices: | |
| writer.writerow(row) | |
| return historical_prices | |
| def main(): | |
| prices = historical_prices('aapl') | |
| if __name__ =='__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment