2024-03-28 09:42:47 发布
网友
我喜欢创建一个熊猫数据表,以跟踪每日、每周、每月和每年的库存变化百分比。 下面是我想要的输出:
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
这是用来生成它的代码。我不熟悉Python和熊猫。有更好的方法吗。另外,我是手工输入日期,可以自动生成吗。在
任何有助于改进此代码的人都将不胜感激。在
谢谢
我相信这会让你达到目的
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)
输出
我相信这会让你达到目的
输出
^{pr2}$相关问题 更多 >
编程相关推荐