"""Reproduce the gs-quant max_drawdown rolling-window issue (gs-quant main @ 0e3cc8e).
pip install gs-quant==2.3.4 ; python gs-quant-max-drawdown-check.py"""
import numpy as np, pandas as pd, warnings
warnings.filterwarnings('ignore')
from gs_quant.timeseries import Window
from gs_quant.timeseries.econometrics import max_drawdown

def reference(x, w):
    v, out = x.values, []
    for t in range(len(v)):
        s = v[max(0, t - w + 1):t + 1]
        out.append((s / np.maximum.accumulate(s) - 1).min())
    return np.array(out)

x = pd.Series([100, 50, 50, 50.], index=pd.date_range('2026-01-01', periods=4))
print('gs-quant, w=3:', max_drawdown(x, Window(3, 0)).values, ' reference:', reference(x, 3))
rng = np.random.default_rng(1)
z = pd.Series(100 * np.exp(np.cumsum(rng.normal(0, .01, 2000))), index=pd.date_range('2020-01-01', periods=2000))
for w in (5, 20, 50, 250):
    d = np.abs(max_drawdown(z, Window(w, 0)).values - reference(z, w))
    print(f'w={w}: max abs error {np.nanmax(d):.3f}, share wrong {np.mean(d > 1e-12):.0%}')
