Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created September 24, 2020 10:48
Embed
What would you like to do?
Pandas Datareader for stock and financial data
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