I like to create a pandas df for tracking % change of stock on daily, weekly, monthly and yearly basis. Here is output what i would like the output to look like:
stock Close Daily WTD MTD YTD
0 IWM 137.960007 0.847956 0.847956 5.337105 25.406785
1 IBM 167.600006 0.551964 0.551964 4.867976 23.280625
Here is the code that used to generate it. I am new to python and panda. Is there a better way of doing this. Also , i am inputing the dates manually, can it be generated automatically.
import pandas as pd
from datetime import datetime, timedelta
from pandas_datareader import data,wb
start = datetime(2016, 1, 1)
end = datetime.today()
m_start = datetime(2016, 12, 1)
w_start = datetime(2016, 12, 19)
d_start = end - timedelta(days=2)
labels = ['stock','Close','Daily','WTD','MTD','YTD']
dat = []
for ticker in ticker_list:
prices = data.DataReader(ticker, 'yahoo', start, end)
closing_prices = prices['Close']
change = 100 * (closing_prices[-1] - closing_prices[0]) / closing_prices[0]
#get the monthly % gain
m_price = data.DataReader(ticker, 'yahoo', m_start, end)
m_close = m_price['Close']
m_change = 100 * (m_close[-1] - m_close[0]) / m_close[0]
#get the weekly % gain
w_price = data.DataReader(ticker, 'yahoo', w_start, end)
w_close = w_price['Close']
w_change = 100 * (w_close[-1] - w_close[0]) / w_close[0]
#get the Daily % gain
d_price = data.DataReader(ticker, 'yahoo', d_start, end)
d_close = d_price['Close']
d_change = 100 * (d_close[-1] - d_close[0]) / d_close[0]
dat.append((ticker,closing_prices[-1],d_change,w_change,m_change,change))
df2 = pd.DataFrame.from_records(dat,columns=labels)
df2
Any help to improve this code is really appreciated.
thanks
I believe this will get you there
Output