基础盈亏计算器
Pnl Basic Calculator
题目详情
盈亏(PnL)是评估任何交易策略表现的基础指标。在量化金融中,准确高效地计算百万级交易的已实现盈亏,对事后分析和实时风控至关重要。
任务:实现盈亏计算器类,计算平仓交易的已实现盈亏。维护持仓数量和平均成本,在平仓时根据卖出价格与平均成本的差值计算盈亏。
英文原题
Profit and Loss (PnL) is the fundamental metric used to evaluate the performance of any trading strategy. Accurately and efficiently calculating realized PnL across millions of trades is critical for post-trade analysis and real-time risk management in quantitative finance.
Task
Implement a PnLCalculator class with a calculateRealizedPnL method that computes the realized profit or loss of a closed trade. The method receives four double parameters: entryPrice, exitPrice, quantity, and side (wher
解析
问题分析
PnL(盈亏)计算是交易系统中最基础的功能。已实现盈亏 = Σ(卖出价 - 买入价) × 数量;未实现盈亏 = (当前市价 - 买入价) × 持仓量。需区分多空方向和不同会计方法(FIFO/LIFO/平均成本)。
解法
struct Trade { double price; int qty; bool is_buy; };
class PnLCalculator {
double realized_{0.0}; int position_{0}; double cost_basis_{0.0};
public:
void onFill(double price, int qty, bool is_buy) {
if (is_buy) { position_ += qty; cost_basis_ += price * qty; }
else { realized_ += (price - cost_basis_/position_) * qty; position_ -= qty; }
}
double unrealized(double market_price) const {
return position_ > 0 ? (market_price - cost_basis_/position_) * position_ : 0.0;
}
double totalPnL(double market_price) const { return realized_ + unrealized(market_price); }
};验证
买入 100@50, 卖出 50@55, 市价 52: realized=(55-50)×50=250, unrealized=(52-50)×50=100, total=350 ✓
复杂度与边界
- 时间复杂度:所有操作 O(1)
- 边界条件:(1) 做空时成本基数为负 (2) 零持仓时 unrealized=0 (3) 部分平仓按比例减少持仓
英文解析
Analysis
PnL (Profit and Loss) calculation is the most fundamental function in trading systems. Realized PnL = sum of (sell_price - buy_price) * quantity; Unrealized PnL = (current_market_price - buy_price) * position. Must distinguish long/short direction and different accounting methods (FIFO/LIFO/average cost).
Solution
struct Trade { double price; int qty; bool is_buy; };
class PnLCalculator {
double realized_{0.0}; int position_{0}; double cost_basis_{0.0};
public:
void onFill(double price, int qty, bool is_buy) {
if (is_buy) { position_ += qty; cost_basis_ += price * qty; }
else { realized_ += (price - cost_basis_/position_) * qty; position_ -= qty; }
}
double unrealized(double market_price) const {
return position_ > 0 ? (market_price - cost_basis_/position_) * position_ : 0.0;
}
double totalPnL(double market_price) const { return realized_ + unrealized(market_price); }
};Verification
Buy 100@50, sell 50@55, market price 52: realized=(55-50)*50=250, unrealized=(52-50)*50=100, total=350.
Complexity & Edge Cases
- Time complexity: All operations O(1)
- Edge cases: (1) Short positions have negative cost basis (2) Zero position: unrealized=0 (3) Partial close reduces position proportionally
Key Considerations
- Realized vs unrealized: P&L must distinguish realized (from closed positions) and unrealized (from open positions marked to market); total P&L = realized + unrealized
- Mark-to-market basis: Unrealized P&L uses current mid-price for marking; bid/ask spread introduces marking ambiguity for large positions
- Fee inclusion: Net P&L must subtract transaction costs (commissions, fees, slippage); gross P&L without fees overstates profitability
- Currency normalization: Multi-currency positions must be converted to base currency for consolidated P&L; exchange rate fluctuation introduces FX P&L component