Pandas Dataframe for Stock % change

3.7k views Asked by At

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

1

There are 1 answers

2
Ted Petrou On BEST ANSWER

I believe this will get you there

tickers = ['IWM', 'IBM']
df_list = []
for ticker in tickers:
    prices = data.DataReader(ticker, 'yahoo', '2016')['Close']

    # get all timestamps for specific lookups
    today = prices.index[-1]
    yest= prices.index[-2]
    start = prices.index[0]
    week = today - pd.tseries.offsets.Week(weekday=0)
    month = today - pd.tseries.offsets.BMonthBegin()

    # calculate percentage changes
    close = prices[today]
    daily =  (close - prices[yest]) / prices[yest] * 100
    wtd = (close - prices[week]) / prices[week] * 100
    mtd = (close - prices[month]) / prices[month] * 100
    ytd = (close - prices[start]) / prices[start]* 100

    # create temporary frame for current ticker
    df = pd.DataFrame(data=[[ticker, close, daily, wtd, mtd,  ytd]], 
                      columns=['stock', 'Close', 'Daily', 'WTD', 'MTD', 'YTD'])
    df_list.append(df)

# stack all frames
pd.concat(df_list)

Output

  stock       Close     Daily       WTD       MTD        YTD
0   IWM  137.960007  0.847956  0.847956  5.337105  25.406785
0   IBM  167.600006  0.551964  0.551964  4.867976  23.280625