VWAP 计算器
Vwap Calculator
题目详情
VWAP(成交量加权平均价)是机构投资者评估交易执行质量的关键基准。它代表证券当天的平均交易价格,通过累计成交金额除以累计成交量计算。
任务:实现 VWAP 计算器类,逐笔更新累计成交量和成交金额,提供获取当前 VWAP 值的方法。支持按时间窗口计算滚动 VWAP。
英文原题
Volume-Weighted Average Price (VWAP) is a crucial trading benchmark used by institutional investors to assess the quality of their trade executions. It represents the average price a security has traded at throughout the day, calculated by dividing the cumulative dollar volume by the cumulative trading volume. Maintaining a running VWAP is essential in algorithmic trading systems for real-time performance evaluation and execution logic.
Task
Implement a VWAPCalculator class that processes a str
解析
问题分析
VWAP(成交量加权平均价格)是机构投资者评估执行质量的核心基准。计算公式为 Σ(price × volume) / Σ(volume)。实现需要以流式方式处理逐笔成交数据,避免一次性加载全部数据。
解法
class VWAPCalculator {
double cum_dollar_vol_{0.0};
uint64_t cum_volume_{0};
public:
void onTrade(double price, uint64_t volume) {
cum_dollar_vol_ += price * volume;
cum_volume_ += volume;
}
double vwap() const { return cum_volume_ > 0 ? cum_dollar_vol_ / cum_volume_ : 0.0; }
void reset() { cum_dollar_vol_ = 0.0; cum_volume_ = 0; }
};验证
输入: (100.0, 100), (101.0, 200), (99.0, 100)
VWAP = (10000 + 20200 + 9900) / 400 = 40100/400 = 100.25 ✓
复杂度与边界
- 时间复杂度:onTrade O(1),vwap O(1)
- 边界条件:(1) 零成交量返回 0 (2) 按日重置 (3) 大成交量需 uint64 防溢出
英文解析
Analysis
VWAP (Volume-Weighted Average Price) is the core benchmark for institutional investors evaluating execution quality. Formula: sum(price * volume) / sum(volume). Implementation must process tick-by-tick trade data in streaming fashion, avoiding loading all data at once.
Solution
class VWAPCalculator {
double cum_dollar_vol_{0.0};
uint64_t cum_volume_{0};
public:
void onTrade(double price, uint64_t volume) {
cum_dollar_vol_ += price * volume;
cum_volume_ += volume;
}
double vwap() const { return cum_volume_ > 0 ? cum_dollar_vol_ / cum_volume_ : 0.0; }
void reset() { cum_dollar_vol_ = 0.0; cum_volume_ = 0; }
};Verification
Input: (100.0, 100), (101.0, 200), (99.0, 100). VWAP = (10000 + 20200 + 9900) / 400 = 40100/400 = 100.25.
Complexity & Edge Cases
- Time complexity: onTrade O(1), vwap O(1)
- Edge cases: (1) Zero volume returns 0 (2) Reset daily (3) Large volume requires uint64 to prevent overflow
Key Considerations
- Volume weighting correctness: VWAP = sum(price × volume) / sum(volume); zero-volume intervals must be excluded, not treated as price=0 entries
- Tick vs trade data: VWAP over trade prints includes only executed trades; VWAP over order book levels uses displayed liquidity — these are fundamentally different metrics
- Self-execution exclusion: When computing benchmark VWAP for strategy evaluation, exclude own trades from the volume sum to avoid circular benchmarking
- Interval boundaries: VWAP over arbitrary time windows requires precise start/end time alignment; clock skew between data feed and execution system produces boundary errors