Last active
April 27, 2018 08:55
-
-
Save lucaslouca/c2f7061e642144d7f635158ef9ca7423 to your computer and use it in GitHub Desktop.
Reads the 10-year historical prices from Nasdaq into a Pandas DataFrame
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 pandas as pd | |
| import csv | |
| def historical_prices(symbol:str): | |
| symbol = symbol.lower() | |
| url = "https://www.nasdaq.com/symbol/{0}/historical".format(symbol) | |
| headers = {'content-type' : 'application/json'} | |
| data = "10y|true|{0}".format(symbol) | |
| historical_prices_df = pd.DataFrame(columns=('date', 'close', 'volume', 'open', 'high', 'low')) | |
| resp = requests.post(url, data=data, headers=headers) | |
| reader = csv.reader(resp.text.split('\n'), delimiter=',') | |
| # Skip the first two rows | |
| next(reader) | |
| next(reader) | |
| for row in reader: | |
| if row: | |
| historical_prices_df.loc[len(historical_prices_df)] = row | |
| # Create a date index | |
| historical_prices_df.set_index('date', inplace=True) | |
| historical_prices_df.index = pd.to_datetime(historical_prices_df.index, format = '%Y/%m/%d') | |
| return historical_prices_df | |
| def main(): | |
| prices_df = historical_prices('aapl') | |
| print(prices_df.head(5)) | |
| if __name__ =='__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment