在熊猫数据帧中每天运行每个类别的总计



我有一个熊猫数据帧,其中包含股票交易,这些交易不是每天都发生,也不是每只股票都发生:

目标是获取每天每只股票的(每日)权重。

起始表和预期结果

这意味着- 创建完整的日期日历- 重复每只股票在每个日期的累计份额- 最后计算这个日期的重量

索蒙能帮我吗?我已经在搜索了几个线程,但我找不到任何有效的解决方案。

谢谢你的问题。当我要为投资构建数据帧时,我尝试了这段代码,所以这是很好的做法。试试这个,我认为它符合您的要求。

import pandas as pd
import datetime
# create df
trades = pd.DataFrame(index=['2011-02-16', '2011-02-16', '2011-02-17', '2014-03-20','2014-03-20', '2018-01-04'])
# build data
trades['stock'] = ['A', 'B', 'A', 'B', 'C', 'B']
trades['shares_Tr'] = [5,10,5,10,15,-20]
# create a range of dates for the balance dataframe
index_of_dates = pd.date_range(('2011-02-10'), ('2018-01-05')).tolist()
# create a balance dataframe with columns for each stock. 
bal = pd.DataFrame(data = 0, index=index_of_dates, columns=['A', 'A_sum', 'A_weight', 'B', 'B_sum', 'B_weight',  'C', 'C_sum', 'C_weight', 'Total' ])
# populate the trades from trades df to the balance df.
for index, row in trades.iterrows():
    bal.loc[index, row['stock']] = row['shares_Tr']
# track totals
bal['A_sum'] = bal['A'].cumsum()
bal['B_sum'] = bal['B'].cumsum()
bal['C_sum'] = bal['C'].cumsum()
bal['Total'] = bal.iloc[:,[1,4,7]].sum(axis=1)
bal['A_weight'] = bal['A_sum'] / bal['Total']
bal['B_weight'] = bal['B_sum'] / bal['Total']
bal['C_weight'] = bal['C_sum'] / bal['Total']

您将有两个数据帧,一个称为交易,另一个称为bal,用于保存您的结果。

太棒了!这启发了我找到解决问题的方法!解决方案中的问题是,如果初始数据集中出现股票 D(在下面的集合中添加),它将不再起作用。

我能够通过以下方式解决此问题:

import pandas as pd
import datetime
# create df // build data // adding date as column
trades = pd.DataFrame()
trades['Date'] = pd.to_datetime(['2011-02-16', '2011-02-16', '2011-02-17', '2014-03-20','2014-03-20', '2018-01-04', '2011-02-18'])
trades['stock'] = ['A', 'B', 'A', 'B', 'C', 'B', 'D']
trades['shares_Tr'] = [5,10,5,10,15,-20,5]
# create a range of dates for the merged dataframe
index_of_dates = pd.date_range('2011-02-10', pd.datetime.today()).to_frame().reset_index(drop=True).rename(columns={0: 'Date'})
# create a merged dataframe with columns date / stock / stock_Tr. 
merged = pd.merge(index_of_dates,trades,how='left', on='Date')
# create a pivottable showing the shares_TR of each stock for each date 
shares_tr = merged.pivot(index='Date', columns='stock', values='shares_Tr').dropna(axis=1, how='all').fillna(0)
# calculate individual pivottables for the cumsum and weights 
cumShares = shares_tr.cumsum()
weights = ((cumShares.T / cumShares.T.sum()).T*100).round(2)
# finally combine all data into one dataframe
all_data = pd.concat([shares_tr, cumShares, weights], axis=1, keys=['Shares','cumShares', 'Weights'])
all_data

相关内容

  • 没有找到相关文章

最新更新