最大回撤计算
Max Drawdown Calculation
题目详情
最大回撤(MDD)衡量资产价值从历史峰值到新峰值出现之前的最大百分比跌幅。该指标在量化风险管理中用于评估交易策略或投资组合的最坏历史损失。
任务:实现最大回撤计算函数,确定价格序列的最大回撤。函数接收价格数组,逐点跟踪历史峰值和当前回撤,返回最大回撤百分比。
英文原题
Maximum Drawdown (MDD) measures the largest percentage decline in an asset's value from a historical peak before a new peak is achieved. This metric is fundamental in quantitative risk management for evaluating the worst-case historical loss of a trading strategy or portfolio.
Task
Implement the calculate_max_drawdown function to determine the maximum drawdown of a price series. The function accepts a list of floats prices representing asset prices ordered by time and returns the maximum percen
解析
问题分析
最大回撤(Maximum Drawdown)衡量投资组合从历史最高点到随后最低点的最大损失百分比。这是最直观的风险指标,直接回答"在最坏情况下会亏多少"。
实现
struct Drawdown { double max_dd_pct; int peak_idx, trough_idx; int duration_days; };
Drawdown computeDrawdown(const std::vector<double>& values) {
Drawdown result{0, 0, 0, 0};
double peak = values[0]; int peak_day = 0, dd_start = 0;
for (int i = 0; i < (int)values.size(); ++i) {
if (values[i] > peak) { peak = values[i]; peak_day = i; dd_start = i; }
else {
double dd = (peak - values[i]) / peak;
if (dd > result.max_dd_pct) {
result = {dd, peak_day, i, i - dd_start};
}
}
}
return result;
}复杂度与边界
- 时间复杂度:O(N) 单次遍历
- 空间复杂度:O(1)
- 边界条件:(1) 空序列需特殊处理 (2) 持续上涨时 max_dd=0 (3) 日内回撤按 tick 计算
英文解析
Analysis
Maximum Drawdown measures the largest percentage loss from a historical peak to the subsequent trough in a portfolio's value. This is the most intuitive risk metric, directly answering the question "the worst loss I could experience?".
Solution
struct Drawdown { double max_dd_pct; int peak_idx, trough_idx; int duration_days; };
Drawdown computeDrawdown(const std::vector<double>& values) {
Drawdown result{0, 0, 0, 0};
double peak = values[0]; int peak_day = 0, dd_start = 0;
for (int i = 0; i < (int)values.size(); ++i) {
if (values[i] > peak) { peak = values[i]; peak_day = i; dd_start = i; }
else {
double dd = (peak - values[i]) / peak;
if (dd > result.max_dd_pct) {
result = {dd, peak_day, i, i - dd_start};
}
}
}
return result;
}Complexity & Edge Cases
- Time complexity: O(N) single pass
- Space complexity: O(1)
- Edge cases: (1) Empty sequence requires special handling (2) Continuously rising values yield max_dd=0 (3) Intraday drawdown computed per tick
Verification
Test with known equity curve where drawdown location is known. Verify peak and trough indices are correct. Test edge case where equity only rises (zero drawdown).
Key Considerations
Maximum drawdown is path-dependent and captures the worst-case investor experience. In risk reporting, drawdown duration (time from peak to recovery) is equally important as magnitude. A 20% drawdown lasting 6 months is far more concerning than a 30% drawdown recovered in 2 weeks.