You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于列条件的Pandas Groupby求和:计算各Symbol持仓盈亏

按Symbol和Entry分组计算盈亏

原始数据

给定的初始DataFrame如下:

import pandas as pd

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']})

处理步骤

1. 转换数值类型

将Quantity和Price列从字符串转为浮点型,用于后续计算:

df[['Quantity', 'Price']] = df[['Quantity', 'Price']].astype(float)

2. 生成交易组标识

以Position列的Entry为分界,为每个独立交易周期(Entry到下一个Entry前)分配唯一组号:

df['Group'] = (df['Position'] == 'Entry').cumsum()

3. 按组统计核心指标

按组聚合,提取每组的标的Symbol、开仓方向(Entry行的Action)、Sell总金额、Buy总金额:

grouped_stats = df.groupby('Group').agg(
    Symbol=('Symbol', 'first'),
    Entry_Action=('Action', 'first'),
    Total_Sell=('Price', lambda x: sum(df.loc[x.index, 'Price'] * df.loc[x.index, 'Quantity'] * (df.loc[x.index, 'Action'] == 'Sell'))),
    Total_Buy=('Price', lambda x: sum(df.loc[x.index, 'Price'] * df.loc[x.index, 'Quantity'] * (df.loc[x.index, 'Action'] == 'Buy')))
).reset_index(drop=True)

4. 计算盈亏

根据每组的开仓方向选择对应公式计算盈亏:

  • 开仓为Sell:盈亏 = 卖出总金额 - 买入总金额
  • 开仓为Buy:盈亏 = 卖出总金额 - 买入总金额(若需调整为买入减卖出,可直接修改公式)
grouped_stats['Profit_Loss'] = grouped_stats.apply(
    lambda row: row['Total_Sell'] - row['Total_Buy'],
    axis=1
)

最终输出

提取Symbol和盈亏结果:

print(grouped_stats[['Symbol', 'Profit_Loss']])

输出结果:

Symbol  Profit_Loss
0     AA          2.2
1     BB          0.4
2     CC         -0.1

内容的提问来源于stack exchange,提问作者skepticalforever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:05:28