Created
September 24, 2020 10:48
-
-
Save yuyasugano/423bc5c9b9a3c916b93d9a01430c8b38 to your computer and use it in GitHub Desktop.
Pandas Datareader for stock and financial data
This file contains 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 datetime | |
import numpy as np | |
import pandas as pd | |
import pandas_datareader.data as pdr | |
# fetch multiple asset data | |
def getMultiAssetData(ticketList, date_from, date_to): | |
def getData(ticker): | |
data = pdr.DataReader(ticker, 'yahoo', date_from, date_to) | |
return data | |
datas = map(getData, tickerList) | |
return pd.concat(datas, keys=tickerList, names=['Ticker', 'Date']) | |
date_from = datetime.date(2018, 1, 1) | |
date_to = datetime.date(2020, 8, 31) | |
tickerList = ['AAPL', 'AMZN', 'FB'] | |
multiData = getMultiAssetData(tickerList, date_from, date_to) | |
# use pivot to reshape DataFrame with only Close | |
ClosePrice = multiData[['Close']] | |
ClosePrice = ClosePrice.reset_index() | |
ClosePriceTable = ClosePrice.pivot(index='Date', columns='Ticker', values='Close') | |
ClosePriceTable.tail() | |
DawJones = pdr.DataReader('^DJI', "stooq", date_from, date_to).sort_index() | |
BondUS = pdr.DataReader('BND.US', "stooq", date_from, date_to).sort_index() | |
df = pd.concat([ClosePriceTable, DawJones['2018-1-1':'2020-08-31']['Close'], BondUS['2018-1-1':'2020-08-31']['Close']], axis=1) | |
df.columns = ['Apple', 'Amazon', 'Facebook', 'DawJones', 'US Bond'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment