净额结算替代对冲下的平均资产价格计算及Pandas实现咨询
计算平均入场/持仓价格的Pandas实现方案
核心逻辑是加权平均成本(Weighted Average Cost, WAC),无论下单量是否递增、价格间隔是否规则,公式统一为:
平均持仓价 = 总买入金额之和 ÷ 总买入数量之和
场景验证
- 基础场景:20000买1单位、19000买1单位,总金额=20000+19000=39000,总数量=2,平均价=39000/2=19500,与示例一致。
- 递增下单量场景:20000买1、19500买1.5、19000买2,总金额=20000×1 + 19500×1.5 + 19000×2=87250,总数量=4.5,平均价≈19388.89。
- 价格不规则场景:20000买1、19000买1、19150买1,总金额=58150,总数量=3,平均价≈19383.33。
Pandas实现方案
1. 基于已有交易历史计算
假设你有记录所有买入交易的DataFrame,包含price(买入价)和quantity(买入量)两列:
import pandas as pd # 示例交易数据(可替换为你的实际数据) trades = pd.DataFrame({ 'price': [20000, 19500, 19000], 'quantity': [1, 1.5, 2] }) # 方法一:手动计算总金额/总数量 trades['amount'] = trades['price'] * trades['quantity'] total_amount = trades['amount'].sum() total_quantity = trades['quantity'].sum() avg_price = total_amount / total_quantity # 方法二:使用Pandas内置加权平均 avg_price = trades['price'].mean(weights=trades['quantity']) print(f"平均入场价: {avg_price:.2f}") print(f"总持仓量: {total_quantity}")
2. 动态更新(逐笔新增交易时)
如果需要每次新增买入后实时更新平均价,可维护累计金额和累计数量,避免重复计算全部历史:
# 初始化累计值 cumulative_amount = 0.0 cumulative_quantity = 0.0 # 模拟逐笔新增交易 new_trades = [ {'price': 20000, 'quantity': 1}, {'price': 19500, 'quantity': 1.5}, {'price': 19000, 'quantity': 2} ] for trade in new_trades: trade_amount = trade['price'] * trade['quantity'] cumulative_amount += trade_amount cumulative_quantity += trade['quantity'] current_avg = cumulative_amount / cumulative_quantity print(f"新增交易后:平均价={current_avg:.2f},持仓量={cumulative_quantity}")
注意事项
- 该逻辑仅适用于买入场景,若包含卖出操作,需根据卖出规则(如先进先出、后进先出或加权平均卖出)调整持仓量和剩余成本。
- 若使用
mean(weights=...),需确保Pandas版本≥1.3.0(该参数从1.3.0开始支持)。
内容的提问来源于stack exchange,提问作者Sergey Sypalo
相关产品推荐
相关产品推荐

