Python Pandas如何基于多条件计算前期、累计与交易成本列
Pandas 分组递推计算持仓成本列实现方案
这类依赖上一行计算结果的递推逻辑,无法直接通过常规向量化操作实现,按ticker分组后逐行维护递推状态即可完成计算,具体实现如下:
实现代码
先确保你已经完成了transacted_value、flow_units、cml_units、prev_units这几个前置列的计算,再运行以下代码:
def calc_group_cost(grp): prev_costs = [] cml_costs = [] cost_transaction = [] # 初始化组内累计成本初始值 current_cml = 0 for _, row in grp.iterrows(): prev_c = current_cml tx_cost = 0 if row['type'] == 'buy': # 买入逻辑:累计成本加本次买入支出 current_cml = prev_c + row['transacted_value'] elif row['type'] == 'sell': # 卖出逻辑:按持仓占比结转卖出成本,累计成本扣减对应部分 tx_cost = round((row['units'] / row['cml_units']) * prev_c, 2) current_cml = prev_c - tx_cost else: # 拆分等其他操作:累计成本保持不变 current_cml = prev_c prev_costs.append(prev_c) cml_costs.append(round(current_cml, 2)) cost_transaction.append(tx_cost) grp['prev_costs'] = prev_costs grp['cml_costs'] = cml_costs grp['cost_transaction'] = cost_transaction return grp # 分组应用计算,关闭group_keys避免生成多层索引 df = df.groupby('ticker', group_keys=False).apply(calc_group_cost)
结果校验
运行代码后,输出三列的结果和你给出的预期值完全一致:
print(df[['prev_costs', 'cml_costs', 'cost_transaction']])
输出:
prev_costs cml_costs cost_transaction 0 0.00 105.00 0.00 1 105.00 210.00 0.00 2 210.00 210.00 0.00 3 210.00 150.00 60.00 4 150.00 223.00 0.00 5 223.00 159.29 63.71 6 159.29 232.29 0.00 7 0.00 127.75 0.00 8 127.75 331.75 0.00
说明:代码中对计算结果做了2位小数四舍五入,和示例预期的精度对齐,如需更高计算精度移除
round处理即可。
内容的提问来源于stack exchange,提问作者Jakob R
相关产品推荐
相关产品推荐

