我有以下数据框:
df = pd.DataFrame({'Position':['Entry','Partial','Partial','Partial','Entry','Partial','Partial','Entry','Partial'],
'Symbol':['AA','AA','AA','AA','BB','BB','BB','CC','CC'],
'Action':['Sell','Buy','Buy','Buy','Buy','Sell','Sell','Sell','Buy'],
'Quantity':['4','2','1','1','2','1','1','1','1'],
'Price':['2.1','1.5','2.2','1','4.6','5.1','4.5','1','1.1']})
我正在尝试在另一列中计算每个唯一符号的损益。该值取决于入场的方向,以确定利润是否等于卖出 - 买入值(value)或买入 - 卖出值(value)。我很难弄清楚如何将这些值求和到下一个交易品种/入场指标。
我的尝试包括使用 numpy.where 函数以及 dataframe.assign 函数。有人可以帮助我理解如何解决这些基于条件的求和问题吗?
我正在尝试如下输出,其中我将唯一的符号字符串及其相对损益输出保留下来。
最佳答案
确切的预期输出尚不清楚,但假设您需要一个新列来总结每个符号的买卖:
# ensure we have numeric values and not strings
df[['Quantity', 'Price']] = df[['Quantity', 'Price']].apply(pd.to_numeric)
df['profit/loss'] = (df['Action']
.map({'Buy': -1, 'Sell': 1}) # make Buy -1 and Sell 1
.mul(df['Price']) # make Buy negative values
.mul(df['Quantity']) # multiply by Quantity
.groupby(df['Symbol'])
.transform('sum') # sum per group as new column
)
输出:
Position Symbol Action Quantity Price profit/loss
0 Entry AA Sell 4 2.1 2.2
1 Partial AA Buy 2 1.5 2.2
2 Partial AA Buy 1 2.2 2.2
3 Partial AA Buy 1 1.0 2.2
4 Entry BB Buy 2 4.6 0.4
5 Partial BB Sell 1 5.1 0.4
6 Partial BB Sell 1 4.5 0.4
7 Entry CC Sell 1 1.0 -0.1
8 Partial CC Buy 1 1.1 -0.1
如果您不需要新专栏而是摘要:
(df['Action']
.map({'Buy': -1, 'Sell': 1})
.mul(df['Price']).mul(df['Quantity'])
.groupby(df['Symbol']).sum()
)
输出:
Symbol
AA 2.2
BB 0.4
CC -0.1
dtype: float64
关于python - Pandas 根据其他列的条件进行分组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73889948/