Python 用于库存百分比更改的数据帧
我喜欢创建一个用于跟踪每日、每周、每月和每年的库存百分比变化的df。 以下是我希望输出看起来像的输出:Python 用于库存百分比更改的数据帧,python,pandas,stock,Python,Pandas,Stock,我喜欢创建一个用于跟踪每日、每周、每月和每年的库存百分比变化的df。 以下是我希望输出看起来像的输出: 股票收盘日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我相信这会让您达到目标 tickers = ['IWM', 'IBM'] df_list = [] for ticker in tickers:
股票收盘日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
我相信这会让您达到目标
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
ticker_list={'IWM':'IWM','IBM':'IBM'}谢谢..这项工作。还有一个简短的问题。到目前为止,对于quartar,我添加了以下内容,但它是从月初开始运行的,而不是从季度开始运行的。**quarter=today-pd.tseries.offsets.BQuarterBegin()**我做错了什么?您必须添加
startmonth=1
。在这里检查问题