# 5.1.2. Max Drawdown

Mục đích: Hàm này **tính mức sụt giảm lớn nhất** từ đỉnh đến đáy trong một cửa sổ trượt (rolling window).

* Nếu trong 1 khoảng thời gian (window), giá cổ phiếu rơi từ đỉnh 100 xuống đáy 80, thì drawdown là `(80 - 100)/100 = -0.2`. Hàm trả về `0.2` (giá trị dương).

Cấu trúc hàm: max\_drawdown(x, w=\<gs\_quant.timeseries.helper.Window object>)

Tham số:

<table><thead><tr><th width="83">Tham số</th><th width="175">Kiểu dữ liệu</th><th>Ý nghĩa</th></tr></thead><tbody><tr><td>x</td><td>Series</td><td>Chuỗi thời gian giá (có thể là giá đóng cửa cổ phiếu, NAV quỹ đầu tư, v.v.).</td></tr><tr><td>w</td><td>Window, int hoặc str</td><td>Cửa sổ trượt dùng để tính drawdown: Window(22, 10) - 22 phiên, bỏ qua 10 phiên đầu để “làm nóng” (ramp-up), int - số lượng quan sát (ví dụ <code>20</code> là 20 phiên), str - kiểu chuỗi ngày như <code>'1m'</code>, <code>'1w'</code>, <code>'22d'</code>,... Nếu không truyền <code>w</code>, hàm sẽ tính drawdown cho toàn bộ chuỗi.</td></tr></tbody></table>

Cách hoạt động:

* Với mỗi cửa sổ `w`, hàm:
  * Tìm **đỉnh cao nhất** trong cửa sổ đó.
  * Tìm **đáy thấp nhất sau đỉnh**.
  * Tính drawdown = `(đáy - đỉnh)/đỉnh` và lấy trị tuyệt đối.

Kết quả trả về:

* Kiểu: `Series`
  * Chuỗi thời gian các giá trị drawdown lớn nhất (theo rolling window).
  * Giá trị nằm trong `[0, 1]`, biểu diễn mức sụt giảm lớn nhất trong mỗi khoảng thời gian.

Ví dụ mẫu tính rolling max drawdown với cửa sổ 22 phiên cho mã cổ phiếu HPG trên tập dữ liệu 1 năm (25/06/2024 - 25/06/2025).

```python
from FiinQuantX import FiinSession
from FiinQuantX.timeseries.econometrics import max_drawdown
from FiinQuantX.timeseries.helper import Window
from datetime import datetime
from dateutil.relativedelta import relativedelta

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

client = FiinSession(
    username=username,
    password=password
).login()

# Lấy dữ liệu giá đóng cửa 1 năm EOD của HPG
data = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["HPG"],
    fields=["close"],
    adjusted=True,
    by="1d",
    from_date=(datetime.now() - relativedelta(years=1)).strftime("%Y-%m-%d")
).get_data()

data.set_index("timestamp", inplace=True)

# Tính rolling max drawdown 22 phiên, bỏ qua 10 phiên đầu (ramp-up)
drawdown_series = max_drawdown(data['close'], w=Window(22, 10))

# Gộp kết quả vào DataFrame ban đầu
data['max_drawdown_22'] = drawdown_series
print(data)
```

Kết quả trả về

```
timestamp           ticker    close  max_drawdown_22
2024-06-25 00:00    HPG     28700.0              NaN
2024-06-26 00:00    HPG     28900.0              NaN
2024-06-27 00:00    HPG     28850.0              NaN
2024-06-28 00:00    HPG     28300.0              NaN
2024-07-01 00:00    HPG     28350.0              NaN
...                 ...         ...              ...
2025-06-19 00:00    HPG     26900.0        -0.022945
2025-06-20 00:00    HPG     27000.0        -0.022945
2025-06-23 00:00    HPG     26850.0        -0.022945
2025-06-24 00:00    HPG     27000.0        -0.022945
2025-06-25 00:00    HPG     27200.0        -0.022945
```

Biểu đồ minh họa (tuỳ chọn)

```python
import matplotlib.pyplot as plt

data[['close', 'max_drawdown_22']].plot(subplots=True, figsize=(12, 6), title=['Close Price', 'Max Drawdown (22 days)'])
plt.tight_layout()
plt.show()
```

<figure><img src="/files/2E50H2xWw8RLItrDClll" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.fiinquant.vn/ham-va-cong-thuc/5.-dinh-luong-and-phan-tich-nang-cao/5.1.-hieu-suat-performance/5.1.2.-max-drawdown.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
