【发布时间】:2023-02-14 02:05:06
【问题描述】:
我正在尝试在一组贸易数据的 python 中创建加权平均价格计算器 (WAP)。我使用了下面的代码,它对合同进行分组,这是我想要的和数量,但价格没有加权,它只是平均。下面是我的代码:
import pandas as pd
df = pd.read_csv("WD_trades1302.csv")
#print(df)
# loc to select headers from data
df2 = df.loc[:, ["UsrName","B/S","Ctrct" , "Qty" , "Prc"]]
#print(df2)
#print(df2)
# search on username to pull trader in
df3 = df.loc[((df['UsrName'] == 'WILL FERRELL'))]
#print(df3)
# groups contract, qty & price but not weighted
df4 = df=df.groupby('Ctrct' , 'UsrName').agg({'Qty':'sum', 'Prc':'mean'}).reset_index()
print(df4)
Result
Ctrct Qty Prc
0 2H230213-4B 13 74.500000
1 2H230213-5A 39 143.354000
2 2H230213-5B 23 158.921429
3 4H230213-6 5 150.110000
4 HH230213-23 110 189.423333
5 HH230213-32 60 186.250000
6 HH230213-33 16 72.000000
7 HH230213-34 25 145.440000
此处您可以看到数据按合约 5B 排序,但加权价格应为 160.8 而不是 158.92。我可以添加什么以获得加权平均值而不仅仅是每份合约的平均值?
【问题讨论】:
-
样本数据在这里真的很有帮助。
标签: python pandas dataframe group-by weighted-average