Pandas Dataframe for Stock%更改

时间:2016-12-21 20:24:57

标签: python pandas stock

我喜欢创建一个pandas df,用于跟踪每日,每周,每月和每年的库存变化百分比。 这是输出我希望输出的样子:



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




以下是用于生成它的代码。我是蟒蛇和熊猫的新手。有没有更好的方法来做到这一点。此外,我手动输入日期,可以自动生成。



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




非常感谢任何改进此代码的帮助。

感谢

1 个答案:

答案 0 :(得分:2)

我相信这会让你到那里

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)

输出

  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