# Tổng quan sản phẩm

**FiinQuant – Thư viện dữ liệu và công cụ phân tích dành cho Python**

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FNeAdhQIwPjwobKvdhtUh%2FFlyer%20(su%CC%9B%CC%89a)%202.png?alt=media&amp;token=b745498c-13fd-4be2-aced-5ac8fa3f7aa9" alt=""><figcaption></figcaption></figure>

### FiinQuant là gì?

FiinQuant là **thư viện dữ liệu và công cụ phân tích** dành cho **Python**, giúp các nhà đầu tư, nhà phân tích và lập trình viên dễ dàng truy cập, xử lý và phân tích dữ liệu tài chính một cách nhanh chóng và chính xác.

**Các tính năng chính của FiinQuant bao gồm:**

* **Nhận dữ liệu quá khứ:** Cho phép truy cập và lấy dữ liệu từ nhà cung cấp dữ liệu tài chính.
* **Nhận dữ liệu khớp lệnh thời gian thực:** Cung cấp khả năng nhận dữ liệu thời gian thực, giúp theo dõi thị trường và cập nhật thông tin liên tục.
* **Nối dữ liệu quá khứ và dữ liệu thời gian thực:** Thư viện cho phép gọi phương thức nối dữ liệu lịch sử từ thời gian cụ thể vào với dữ liệu thời gian thực theo các bước thời gian (timeframe) khác nhau.
* **Tạo chỉ báo kỹ thuật:** Cung cấp các công cụ để xây dựng và tính toán các chỉ báo kỹ thuật từ đơn giản như giá trị các đường trung bình (SMA, EMA,...) đến phức tạp hơn như RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Ichimoku và nhiều chỉ báo khác.

Với khả năng kết hợp giữa việc thu thập dữ liệu, xử lý Realtime và phân tích chỉ số, FiinQuant là một giải pháp toàn diện cho các chuyên gia và nhà đầu tư trong lĩnh vực tài chính để nghiên cứu thị trường, từ đó hỗ trợ đưa ra các quyết định đầu tư hiệu quả.


# Điểm nổi bật

### Dữ liệu giao dịch nguồn chính thống

FiinQuant tích hợp trực tiếp dữ liệu thị trường từ các sở giao dịch (HOSE, HNX, UPCOM) theo thời gian thực, đảm bảo tính chính xác, minh bạch và đáng tin cậy cho các ứng dụng phân tích, giao dịch và nghiên cứu.

### Kết nối WebSocket realtime

FiinQuant hỗ trợ kết nối WebSocket ổn định và hiệu suất cao, cho phép:

* Nhận dữ liệu tick-by-tick hoặc cập nhật theo batch (VD: 1s, 5s, 1min)
* Push dữ liệu tự động vào dashboard, bot, hệ thống cảnh báo
* Đồng bộ liên tục với dữ liệu lịch sử để phục vụ các hệ thống phức tạp

Websocket tích hợp cho module giá lẫn module sổ lệnh.

### Dữ liệu tổng hợp sẵn theo từng phút

Hệ thống hỗ trợ dữ liệu tick by tick cho đến từng phút với đầy đủ timeframe 1' 5' 15' 1h 4h 1D cho phép người dùng gọi trực tiếp, không cần duy trì hệ thống server để lưu các dữ liệu lịch sử

### Sẵn sàng kết hợp dữ liệu lịch sử và realtime

FiinQuant cung cấp sẵn các hàm merge và đồng bộ dữ liệu lịch sử và realtime, giúp việc phát triển chiến lược, kiểm thử mô hình (backtest) và triển khai giao dịch dễ dàng và mượt mà.

### **Dữ liệu dòng tiền thông minh – realtime & lịch sử**

Bao gồm các chỉ báo chủ động như:

* BU-SD: Giá trị mua bán ròng của nhà đầu tư tổ chức/chủ động.
* NĐTNN: Hoạt động của nhà đầu tư nước ngoài realtime và theo chuỗi thời gian.

  \=> Hữu ích cho việc xác định dòng tiền lớn và xu hướng thị trường ngắn hạn – trung hạn.

### Tích hợp bộ chỉ báo phân tích kỹ thuật (TA) phổ biến

Thư viện tích hợp sẵn các bộ chỉ báo như:

* MA, EMA, RSI, MACD, Bollinger Bands
* Breakout Signals, Divergence
* Volume Profile và các nhóm chỉ báo hành vi thị trường

### Hàm tài chính nâng cao dành cho nhà đầu tư chuyên nghiệp

FiinQuant cung cấp nhiều hàm tiện ích sẵn sàng triển khai:

* Stock prediction: Dự báo xu hướng giá cổ phiếu bằng ML
* Similar chart: Tìm kiếm cổ phiếu có mô hình tương đồng
* Rebalance index: Tái cơ cấu danh mục chỉ số theo định kỳ hoặc tín hiệu
* Factor models: Phân tích yếu tố ảnh hưởng đến hiệu suất cổ phiếu
* Cập nhật định kỳ liên tục các mô hình tài chính khác

> **Sử dụng thư viện FiinQuant không đơn thuần là công cụ truy xuất dữ liệu, còn là sử dụng hệ sinh thái các công cụ định lượng được xây dựng sẵn dành cho các nhà đầu tư.**


# Dành cho doanh nghiệp

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FmXTGZ9LLV1PMok4uswyD%2Fimage.png?alt=media&amp;token=9a249a27-6af0-438f-9e3d-212edadad398" alt=""><figcaption><p>Tích hợp dữ liệu thị trường toàn diện vào ứng dụng của doanh nghiệp một cách mượt mà, giúp đưa ra quyết định chính xác và nâng cao trải nghiệm người dùng.</p></figcaption></figure>

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FQcPvruixvTnVLjG4a5iG%2Fimage.png?alt=media&amp;token=d1848f0d-1065-4662-9ff4-771cd824e24e" alt=""><figcaption></figcaption></figure>


# Dành cho đào tạo

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FkaHZVhcif4OFwA7s6Wor%2Fimage.png?alt=media&amp;token=34101086-07b3-4256-a3dc-6f4539261d1c" alt=""><figcaption><p>Khơi dậy đam mê khám phá và phát triển tư duy sáng tạo với nguồn dữ liệu thị trường lịch sử, theo thời gian thực với những mẫu dự án sẵn có.</p></figcaption></figure>


# Thông tin liên hệ

**- Kênh nhận tín hiệu Cổ phiếu miễn phí Alpha Radar trên Telegram:** [**https://t.me/canhbaolenh**](https://t.me/canhbaolenh)

**- Địa chỉ liên hệ:**

* Tại Hà Nội: Công ty Cổ phần FiinGroup Việt Nam , Head Office , 10th Floor, Peakview Tower, 36 Hoang Cau Street, O Cho Dua Ward, Hanoi, Vietnam
* Tại Hồ Chí Minh: Suite 1682, Level 16, Bitexco Financial Tower, 02 Hai Trieu Street, Saigon Ward, Ho Chi Minh City, Vietnam

**- Thời gian làm việc:** *Từ 08h30 đến 18h00 các ngày từ thứ Hai đến thứ Sáu hàng tuần.*

* Bộ phận chăm sóc khách hàng:
  * Mobile: 0886911000
  * Email: <info@fiinquant.vn>


# Cài đặt và chuẩn bị

Hướng dẫn dành cho người mới làm quen với Python cũng như lập trình viên.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F6PAxBKA38NyJHWcZxNYK%2Fimage.png?alt=media&amp;token=f0ee8bed-67e0-47eb-a8e3-e75d3411a014" alt=""><figcaption></figcaption></figure>

### 1. Cài đặt Python trên Windows 🖥️

Cài đặt từ Python.org (Khuyến nghị)

{% stepper %}
{% step %}
**📌  Tải Python**

&#x20;Truy cập [Trang chủ Python](https://www.python.org/downloads/windows/)

Nhấn Download Python (Phiên bản mới nhất)
{% endstep %}

{% step %}
**📌 Cài đặt Python**

Mở file .exe vừa tải về.

Chọn “Add Python to PATH”

Nhấn Install Now và đợi quá trình cài đặt hoàn tất.
{% endstep %}

{% step %}
**📌 Kiểm tra cài đặt**

Mở Command Prompt (CMD) và nhập:

```
python --version
```

{% endstep %}
{% endstepper %}

### 2. Cài đặt thư viện FiinQuant. <a href="#cai-dat-thu-vien-fiinquant" id="cai-dat-thu-vien-fiinquant"></a>

```
pip install --extra-index-url https://fiinquant.github.io/fiinquantx/simple fiinquantx
```

Cập nhật thư viện khi có phiên bản mới.

```
pip install --upgrade --extra-index-url https://fiinquant.github.io/fiinquantx/simple fiinquantx
```

### 3. Skill cài đặt và sử dụng thư viện FiinQuant <a href="#cai-dat-thu-vien-fiinquant" id="cai-dat-thu-vien-fiinquant"></a>

Skill hướng dẫn sử dụng, mô tả cấu hình, tối ưu các hàm trong FiinQuant. Phù hợp sử dụng với mọi hệ thống Agentic Coding như Claude, Codex, Antigravity, OpenCode, Cursor...

Cách dùng: Người dùng gửi link dưới đây vào các hệ thống Agentic Coding để AI Agent đọc hiểu và thực hiện việc lập trình xây dựng ứng dụng với thư viện FiinQuant.

<https://github.com/FiinGroup/FiinQuant.git>

{% embed url="<https://github.com/FiinGroup/FiinQuant>" %}

**Lưu ý:** KHÔNG ĐẶT TÊN CÁC FILE SCRIPT PYTHON TRÙNG VỚI TÊN THƯ VIỆN (FiinQuant).\ <br>


# Đăng nhập tài khoản

**Quản lý phiên đăng nhập**

<br>

| Tham số  | Mô tả                        |
| -------- | ---------------------------- |
| username | Tên đăng nhập của người dùng |
| password | Mật khẩu của người dùng      |

**Phương thức**

| Tên phương thức                               | Mã lỗi | Mô tả                                    |
| --------------------------------------------- | ------ | ---------------------------------------- |
| User does not exist (Tài khoản không tồn tại) | 400    | <p>Người dùng nhập sai username.<br></p> |
| Incorrect password (Mật khẩu không đúng)      | 400    | Người dùng nhập sai password.            |

Truy cập phiên đăng nhập

<pre class="language-python"><code class="lang-python"><strong>from FiinQuantX import FiinSession
</strong>

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

client = FiinSession(
    username=username,
    password=password,
).login()
</code></pre>


# Danh sách các phiên bản

## Version 0.1.60 (mới nhất)

* Bổ sung dữ liệu số hợp đồng mở cho các mã phái sinh ở hàm phân loại giao dịch theo nhà đầu tư - [1.8. Lấy dữ liệu giao dịch theo nhà đầu tư](/ham-va-cong-thuc/1.-danh-muc-and-thong-tin-co-ban/1.8.-lay-du-lieu-giao-dich-theo-nha-dau-tu).

## Version 0.1.53

* Dữ liệu phân loại giao dịch theo nhà đầu tư - [1.8. Lấy dữ liệu giao dịch theo nhà đầu tư](/ham-va-cong-thuc/1.-danh-muc-and-thong-tin-co-ban/1.8.-lay-du-lieu-giao-dich-theo-nha-dau-tu).
* Dữ liệu bộ lọc cổ phiếu - [10. Bộ lọc cổ phiếu](/ham-va-cong-thuc/10.-bo-loc-co-phieu).

## Version 0.1.50

* Dữ liệu lịch sử - [2.2. Hàm dữ liệu Lịch sử](/ham-va-cong-thuc/2.-du-lieu-giao-dich/2.2.-ham-du-lieu-lich-su) và dữ liệu Realtime kết hợp lịch sử - [2.3. Hàm nối dữ liệu Realtime và lịch sử](/ham-va-cong-thuc/2.-du-lieu-giao-dich/2.3.-ham-noi-du-lieu-realtime-va-lich-su) có thêm giá trị giao dịch.
* Dữ liệu vốn hóa - [1.4. Lấy dữ liệu vốn hóa](/ham-va-cong-thuc/1.-danh-muc-and-thong-tin-co-ban/1.4.-lay-du-lieu-von-hoa), dữ liệu room nhà đầu tư nước ngoái - [1.5. Lấy dữ liệu room NĐTNN](/ham-va-cong-thuc/1.-danh-muc-and-thong-tin-co-ban/1.5.-lay-du-lieu-room-ndtnn) có thêm dữ liệu realtime khi gọi trong phiên giao dịch

## Version 0.1.49

* Có thêm các chỉ số TA: Point of Control (POC) - [/pages/bZmU7JgfMtgSWiOdJAd3#id-8.4.7.-point-of-control-poc](https://docs.fiinquant.vn/tai-lieu-ki-thuat/pages/bZmU7JgfMtgSWiOdJAd3#id-8.4.7.-point-of-control-poc "mention"), Coppock Curve - [/pages/K0YyCejXEcX8HqoTHg9Z#id-8.2.12.-coppock-curve](https://docs.fiinquant.vn/tai-lieu-ki-thuat/pages/K0YyCejXEcX8HqoTHg9Z#id-8.2.12.-coppock-curve "mention"), Fibonacci - [/pages/apsq1TKpFeQEYcFsOy0n#id-8.8.1.-fibonacci-retracement](https://docs.fiinquant.vn/tai-lieu-ki-thuat/pages/apsq1TKpFeQEYcFsOy0n#id-8.8.1.-fibonacci-retracement "mention"), TRIX - [/pages/64TYL6o6jXfDXbskVTOC#id-8.1.21.-trix](https://docs.fiinquant.vn/tai-lieu-ki-thuat/pages/64TYL6o6jXfDXbskVTOC#id-8.1.21.-trix "mention") và Chaikin Money Flow (CMF) - [/pages/vOXDoEf4WDu4HX3s6vuT#id-8.7.2.-chaikin-money-flow-cmf](https://docs.fiinquant.vn/tai-lieu-ki-thuat/pages/vOXDoEf4WDu4HX3s6vuT#id-8.7.2.-chaikin-money-flow-cmf "mention")
* Sửa tham số RRG chỉ cần truyền đúng tham số period, from\_date cần tính thay vì phải lùi thêm về 33 period hoặc 33 ngày mới bắt đầu tính được cho toàn bộ khoảng thời gian cần tính.
* Hàm dữ liệu lịch sử thêm tính năng gọi dữ liệu sector index đối với timeframe 1D.


# Danh sách dữ liệu hiện có

| Nhóm dữ liệu             | Chi tiết                                                                                                        | Tình trạng                                                                  |
| ------------------------ | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| **Giá & Khối lượng**     | OHLCV (Open - High - Low - Close - Volume), dữ liệu realtime & lịch sử.                                         | <p>EOD</p><p>Tick by Tick (Websocket)</p><p>Intraday (1' 5' 15' 1h 4h) </p> |
| **Sổ lệnh (Order Book)** | Dữ liệu 3/10 mức giá mua – bán, volume bid/ask.                                                                 | Tick by Tick (Websocket)                                                    |
| **Dòng tiền chủ động**   | Mua chủ động/Bán chủ động                                                                                       | <p>EOD</p><p>Tick by Tick (Websocket)</p><p>Intraday (1' 5' 15' 1h 4h)</p>  |
| **Giao dịch khối ngoại** | Mua bán ròng theo từng mã                                                                                       | <p>EOD</p><p>Tick by Tick (Websocket)</p><p>Intraday (1' 5' 15' 1h 4h)</p>  |
| **Chỉ số tái cân bằng**  | Danh sánh mã theo rổ chỉ số. Chỉ số Freeloat, Outstanding Share, Marketcap Limit đối với các mã trong rổ chỉ số | EOD                                                                         |
| **Bộ chỉ số PTKT**       |                                                                                                                 | <p>EOD</p><p>Tick by Tick (Websocket)</p><p>Intraday (1' 5' 15' 1h 4h)</p>  |


# 1. Danh mục & Thông tin cơ bản


# 1.1. Danh sách mã theo index

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Bằng cách nhập vào tên INDEX (Ví dụ: VN30, VN100, VNINDEX, HNXINDEX, v.v.) hàm sẽ trả ra 1 danh sách các mã thuộc INDEX đó, điều này sẽ thuận tiện cho người dùng muốn gọi dữ liệu lịch sử của các mã thuộc cùng 1 rổ INDEX.

Code mẫu:

```python
from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

tickers = client.TickerList(ticker="VN30")
print(tickers)
```

Kết quả trả ra:

\['ACB', 'BID', 'BCM', 'BVH', 'CTG', 'FPT', 'GAS', 'HDB', 'HPG', 'LPB', 'MBB', 'MSN', 'MWG', 'VHM', 'PLX', 'SAB', 'SSB', 'SHB', 'SSI', 'STB', 'TCB', 'TPB', 'VCB', 'VIB', 'VIC', 'VJC', 'VNM', 'GVR', 'VPB', 'VRE']

Ví dụ về việc lấy dữ liệu OHLCV lịch sử của các mã thuộc rổ VN30:

```python
from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

tickers = client.TickerList(ticker="VN30")

data = client.Fetch_Trading_Data(
    realtime=False,
    tickers=tickers,
    fields=["open","high","low","close","volume"],
    adjusted=True,
    by="1d",
    from_date="2025-06-18"
).get_data()

print(data)
```


# 1.2. Danh sách mã theo ngành

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Bằng cách nhập vào tên phân ngành (Ví dụ: BANKS\_L2, REAL\_ESTATE\_L2, STEEL\_L4, OIL\_AND\_GAS\_L2, v.v.) hoặc ICB Code (Ví dụ: 8300, 8600, 1757, 0500, v.v.) hàm sẽ trả ra 1 danh sách các mã thuộc phân ngành đó, điều này sẽ thuận tiện cho người dùng muốn gọi dữ liệu lịch sử của các mã thuộc cùng 1 phân ngành để theo dõi danh mục.

Code mẫu:

```python
from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

tickers = client.TickerList(ticker="BANKS_L2")
print(tickers)
```

Kết quả trả ra:

\['ABB', 'ACB', 'BAB', 'BID', 'BVB', 'CTG', 'EIB', 'HDB', 'KLB', 'LPB', 'MBB', 'MSB', 'NAB', 'NVB', 'OCB', 'PGB', 'SGB', 'SHB', 'SSB', 'STB', 'TCB', 'TPB', 'VAB', 'VBB', 'VCB', 'VIB', 'VPB']

Ví dụ về việc lấy dữ liệu OHLCV lịch sử của các mã thuộc phân ngành ngân hàng L2:

```python
from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

tickers = client.TickerList(ticker="BANKS_L2")

data = client.Fetch_Trading_Data(
    realtime=False,
    tickers=tickers,
    fields=["open","high","low","close","volume"],
    adjusted=True,
    by="1d",
    from_date="2025-06-18"
).get_data()

print(data)
```

Để điền các phân ngành khác, có thể tham khảo bảng tra cứu tên phân ngành truyền vào hàm và ICB Code sau:

```markdown
| Tên phân ngành                                                    | Biến tên phân ngành truyền vào hàm TickerList   | ICB Code truyền vào hàm TickerList |
|-------------------------------------------------------------------|-------------------------------------------------|------------------------------------|
| Dầu khí L1                                                        | OIL_AND_GAS_L1                                  | 0001                               |
| Dầu khí L2                                                        | OIL_AND_GAS_L2                                  | 0500                               |
| Sản xuất Dầu khí L3                                               | OIL_AND_GAS_PRODUCERS_L3                        | 0530                               |
| Sản xuất và Khai thác dầu khí L4                                  | EXPLORATION_AND_PRODUCTION_L4                   | 0533                               |
| Tổ hợp Dầu khí L4                                                 | INTEGRATED_OIL_AND_GAS_L4                       | 0537                               |
| Thiết bị, Dịch vụ và Phân phối Dầu khí L3                         | OIL_EQUIPMENT_SERVICES_AND_DISTRIBUTION_L3      | 0570                               |
| Thiết bị và Dịch vụ Dầu khí L4                                    | OIL_EQUIPMENT_AND_SERVICES_L4                   | 0573                               |
| Ống dẫn Dầu L4                                                    | PIPELINES_L4                                    | 0577                               |
| Nguyên vật liệu L1                                                | BASIC_MATERIALS_L1                              | 1000                               |
| Hóa chất L2                                                       | CHEMICALS_L2                                    | 1300                               |
| Hóa chất L3                                                       | CHEMICALS_L3                                    | 1350                               |
| Nhựa, cao su & sợi L4                                             | COMMODITY_CHEMICALS_L4                          | 1353                               |
| Sản phẩm hóa dầu, Nông dược & Hóa chất khác L4                    | SPECIALTY_CHEMICALS_L4                          | 1357                               |
| Tài nguyên Cơ bản L2                                              | BASIC_RESOURCES_L2                              | 1700                               |
| Lâm nghiệp và Giấy L3                                             | FORESTRY_AND_PAPER_L3                           | 1730                               |
| Lâm sản và Chế biến gỗ L4                                         | FORESTRY_L4                                     | 1733                               |
| Sản xuất giấy L4                                                  | PAPER_L4                                        | 1737                               |
| Kim loại L3                                                       | INDUSTRIAL_METALS_AND_MINING_L3                 | 1750                               |
| Nhôm L4                                                           | ALUMINUM_L4                                     | 1753                               |
| Kim Loại màu L4                                                   | NONFERROUS_METALS_L4                            | 1755                               |
| Thép và sản phẩm thép L4                                          | STEEL_L4                                        | 1757                               |
| Khai khoáng L3                                                    | MINING_L3                                       | 1770                               |
| Khai thác Than L4                                                 | COAL_L4                                         | 1771                               |
| Đá quý và Kim cương L4                                            | DIAMONDS_AND_GEMSTONES_L4                       | 1773                               |
| Khai khoáng L4                                                    | GENERAL_MINING_L4                               | 1775                               |
| Khai thác vàng L4                                                 | GOLD_MINING_L4                                  | 1777                               |
| Bạch kim & Kim loại quý khác L4                                   | PLATINUM_AND_PRECIOUS_METALS_L4                 | 1779                               |
| Công nghiệp L1                                                    | INDUSTRIALS_L1                                  | 2000                               |
| Xây dựng và Vật liệu L2                                           | CONSTRUCTION_AND_MATERIALS_L2                   | 2300                               |
| Xây dựng và Vật liệu L3                                           | CONSTRUCTION_AND_MATERIALS_L3                   | 2350                               |
| Vật liệu xây dựng & Nội thất L4                                   | BUILDING_MATERIALS_AND_FIXTURES_L4              | 2353                               |
| Xây dựng L4                                                       | HEAVY_CONSTRUCTION_L4                           | 2357                               |
| Hàng & Dịch vụ Công nghiệp L2                                     | INDUSTRIAL_GOODS_AND_SERVICES_L2                | 2700                               |
| Hàng không & Quốc phòng L3                                        | AEROSPACE_AND_DEFENSE_L3                        | 2710                               |
| Công nghiệp hàng không L4                                         | AEROSPACE_L4                                    | 2713                               |
| Quốc phòng L4                                                     | DEFENSE_L4                                      | 2717                               |
| Hàng công nghiệp L3                                               | GENERAL_INDUSTRIALS_L3                          | 2720                               |
| Containers & Đóng gói L4                                          | CONTAINERS_AND_PACKAGING_L4                     | 2723                               |
| Công nghiệp phức hợp L4                                           | DIVERSIFIED_INDUSTRIALS_L4                      | 2727                               |
| Điện tử & Thiết bị điện L3                                        | ELECTRONIC_AND_ELECTRICAL_EQUIPMENT_L3          | 2730                               |
| Hàng điện & điện tử L4                                            | ELECTRICAL_COMPONENTS_AND_EQUIPMENT_L4          | 2733                               |
| Thiết bị điện L4                                                  | ELECTRONIC_EQUIPMENT_L4                         | 2737                               |
| Công nghiệp nặng L3                                               | INDUSTRIAL_ENGINEERING_L3                       | 2750                               |
| Xe tải & Đóng tàu L4                                              | COMMERCIAL_VEHICLES_AND_TRUCKS_L4               | 2753                               |
| Máy công nghiệp L4                                                | INDUSTRIAL_MACHINERY_L4                         | 2757                               |
| Vận tải L3                                                        | INDUSTRIAL_TRANSPORTATION_L3                    | 2770                               |
| Chuyển phát nhanh L4                                              | DELIVERY_SERVICES_L4                            | 2771                               |
| Vận tải Thủy L4                                                   | MARINE_TRANSPORTATION_L4                        | 2773                               |
| Đường sắt L4                                                      | RAILROADS_L4                                    | 2775                               |
| Kho bãi, hậu cần và bảo dưỡng L4                                  | TRANSPORTATION_SERVICES_L4                      | 2777                               |
| Dịch vụ vận tải L4                                                | TRUCKING_L4                                     | 2779                               |
| Tư vấn & Hỗ trợ Kinh doanh L3                                     | SUPPORT_SERVICES_L3                             | 2790                               |
| Tư vấn & Hỗ trợ KD L4                                             | BUSINESS_SUPPORT_SERVICES_L4                    | 2791                               |
| Đào tạo & Việc làm L4                                             | BUSINESS_TRAINING_AND_EMPLOYMENT_AGENCIES_L4    | 2793                               |
| Quản lý Tài chính L4                                              | FINANCIAL_ADMINISTRATION_L4                     | 2795                               |
| Nhà cung cấp thiết bị L4                                          | INDUSTRIAL_SUPPLIERS_L4                         | 2797                               |
| Chất thải & Môi trường L4                                         | WASTE_AND_DISPOSAL_SERVICES_L4                  | 2799                               |
| Hàng Tiêu dùng L1                                                 | CONSUMER_GOODS_L1                               | 3000                               |
| Ô tô và phụ tùng L2                                               | AUTOMOBILES_AND_PARTS_L2                        | 3300                               |
| Ô tô và phụ tùng L3                                               | AUTOMOBILES_AND_PARTS_L3                        | 3350                               |
| Sản xuất ô tô L4                                                  | AUTOMOBILES_L4                                  | 3353                               |
| Phụ tùng ô tô L4                                                  | AUTO_PARTS_L4                                   | 3355                               |
| Lốp xe L4                                                         | TIRES_L4                                        | 3357                               |
| Thực phẩm và đồ uống L2                                           | FOOD_AND_BEVERAGE_L2                            | 3500                               |
| Bia và đồ uống L3                                                 | BEVERAGES_L3                                    | 3530                               |
| Sản xuất bia L4                                                   | BREWERS_L4                                      | 3533                               |
| Vang & Rượu mạnh L4                                               | DISTILLERS_AND_VINTNERS_L4                      | 3535                               |
| Đồ uống & giải khát L4                                            | SOFT_DRINKS_L4                                  | 3537                               |
| Sản xuất thực phẩm L3                                             | FOOD_PRODUCERS_L3                               | 3570                               |
| Nuôi trồng nông & hải sản L4                                      | FARMING_AND_FISHING_L4                          | 3573                               |
| Thực phẩm L4                                                      | FOOD_PRODUCTS_L4                                | 3577                               |
| Hàng cá nhân & Gia dụng L2                                        | PERSONAL_AND_HOUSEHOLD_GOODS_L2                 | 3700                               |
| Hàng gia dụng L3                                                  | HOUSEHOLD_GOODS_AND_HOME_CONSTRUCTION_L3        | 3720                               |
| Đồ gia dụng lâu bền L4                                            | DURABLE_HOUSEHOLD_PRODUCTS_L4                   | 3722                               |
| Đồ gia dụng một lần L4                                            | NONDURABLE_HOUSEHOLD_PRODUCTS_L4                | 3724                               |
| Thiết bị gia dụng L4                                              | FURNISHINGS_L4                                  | 3726                               |
| Xây nhà L4                                                        | HOME_CONSTRUCTION_L4                            | 3728                               |
| Hàng hóa giải trí L3                                              | LEISURE_GOODS_L3                                | 3740                               |
| Điện tử tiêu dùng L4                                              | CONSUMER_ELECTRONICS_L4                         | 3743                               |
| Sản phẩm nghệ thuật L4                                            | RECREATIONAL_PRODUCTS_L4                        | 3745                               |
| Đồ chơi L4                                                        | TOYS_L4                                         | 3747                               |
| Hàng cá nhân L3                                                   | PERSONAL_GOODS_L3                               | 3760                               |
| Hàng May mặc L4                                                   | CLOTHING_AND_ACCESSORIES_L4                     | 3763                               |
| Giầy dép L4                                                       | FOOTWEAR_L4                                     | 3765                               |
| Hàng cá nhân L4                                                   | PERSONAL_PRODUCTS_L4                            | 3767                               |
| Thuốc lá L3                                                       | TOBACCO_L3                                      | 3780                               |
| Thuốc lá L4                                                       | TOBACCO_L4                                      | 3785                               |
| Dược phẩm và Y tế L1                                              | HEALTH_CARE_L1                                  | 4000                               |
| Y tế L2                                                           | HEALTH_CARE_L2                                  | 4500                               |
| Thiết bị và Dịch vụ Y tế L3                                       | HEALTH_CARE_EQUIPMENT_AND_SERVICES_L3           | 4530                               |
| Chăm sóc y tế L4                                                  | HEALTH_CARE_PROVIDERS_L4                        | 4533                               |
| Thiết bị y tế L4                                                  | MEDICAL_EQUIPMENT_L4                            | 4535                               |
| Dụng cụ y tế L4                                                   | MEDICAL_SUPPLIES_L4                             | 4537                               |
| Dược phẩm L3                                                      | PHARMACEUTICALS_AND_BIOTECHNOLOGY_L3            | 4570                               |
| Công nghệ sinh học L4                                             | BIOTECHNOLOGY_L4                                | 4573                               |
| Dược phẩm L4                                                      | PHARMACEUTICALS_L4                              | 4577                               |
| Dịch vụ Tiêu dùng L1                                              | CONSUMER_SERVICES_L1                            | 5000                               |
| Bán lẻ L2                                                         | RETAIL_L2                                       | 5300                               |
| Phân phối thực phẩm & dược phẩm L3                                | FOOD_AND_DRUG_RETAILERS_L3                      | 5330                               |
| Phân phối dược phẩm L4                                            | DRUG_RETAILERS_L4                               | 5333                               |
| Phân phối thực phẩm L4                                            | FOOD_RETAILERS_AND_WHOLESALERS_L4               | 5337                               |
| Bán lẻ L3                                                         | GENERAL_RETAILERS_L3                            | 5370                               |
| Bán lẻ hàng may mặc L4                                            | APPAREL_RETAILERS_L4                            | 5371                               |
| Bán lẻ phức hợp L4                                                | BROADLINE_RETAILERS_L4                          | 5373                               |
| Phân phối nội thất L4                                             | HOME_IMPROVEMENT_RETAILERS_L4                   | 5375                               |
| Dịch vụ tiêu dùng chuyên ngành L4                                 | SPECIALIZED_CONSUMER_SERVICES_L4                | 5377                               |
| Phân phối hàng chuyên dụng L4                                     | SPECIALTY_RETAILERS_L4                          | 5379                               |
| Truyền thông L2                                                   | MEDIA_L2                                        | 5500                               |
| Truyền thông L3                                                   | MEDIA_L3                                        | 5550                               |
| Giải trí & Truyền thông L4                                        | BROADCASTING_AND_ENTERTAINMENT_L4               | 5553                               |
| Dịch vụ truyền thông L4                                           | MEDIA_AGENCIES_L4                               | 5555                               |
| Sách, ấn bản & sản phẩm văn hóa L4                                | PUBLISHING_L4                                   | 5557                               |
| Du lịch và Giải trí L2                                            | TRAVEL_AND_LEISURE_L2                           | 5700                               |
| Du lịch & Giải trí L3                                             | TRAVEL_AND_LEISURE_L3                           | 5750                               |
| Dịch vụ hàng không L4                                             | AIRLINES_L4                                     | 5751                               |
| Gambling L4                                                       | GAMBLING_L4                                     | 5752                               |
| Khách sạn L4                                                      | HOTELS_L4                                       | 5753                               |
| Dịch vụ giải trí L4                                               | RECREATIONAL_SERVICES_L4                        | 5755                               |
| Nhà hàng và quán bar L4                                           | RESTAURANTS_AND_BARS_L4                         | 5757                               |
| Vận tải hành khách & Du lịch L4                                   | TRAVEL_AND_TOURISM_L4                           | 5759                               |
| Viễn thông L1                                                     | TELECOMMUNICATIONS_L1                           | 6000                               |
| Viễn thông L2                                                     | TELECOMMUNICATIONS_L2                           | 6500                               |
| Viễn thông cố định L3                                             | FIXED_LINE_TELECOMMUNICATIONS_L3                | 6530                               |
| Viễn thông cố định L4                                             | FIXED_LINE_TELECOMMUNICATIONS_L4                | 6535                               |
| Viễn thông di động L3                                             | MOBILE_TELECOMMUNICATIONS_L3                    | 6570                               |
| Viễn thông di động L4                                             | MOBILE_TELECOMMUNICATIONS_L4                    | 6575                               |
| Tiện ích Cộng đồng L1                                             | UTILITIES_L1                                    | 7000                               |
| Điện, nước & xăng dầu khí đốt L2                                  | UTILITIES_L2                                    | 7500                               |
| Sản xuất & Phân phối Điện L3                                      | ELECTRICITY_L3                                  | 7530                               |
| Sản xuất & Phân phối Điện L4                                      | CONVENTIONAL_ELECTRICITY_L4                     | 7535                               |
| Nước & Khí đốt L3                                                 | GAS_WATER_AND_MULTI-UTILITIES_L3                | 7570                               |
| Phân phối xăng dầu & khí đốt L4                                   | GAS_DISTRIBUTION_L4                             | 7573                               |
| Tiện ích khác L4                                                  | MULTIUTILITIES_L4                               | 7575                               |
| Nước L4                                                           | WATER_L4                                        | 7577                               |
| Tài chính L1                                                      | FINANCIALS_L1                                   | 8000                               |
| Ngân hàng L2                                                      | BANKS_L2                                        | 8300                               |
| Ngân hàng L1                                                      | BANKS_L1                                        | 8301                               |
| Ngân hàng L3                                                      | BANKS_L3                                        | 8350                               |
| Ngân hàng L4                                                      | BANKS_L4                                        | 8355                               |
| Bảo hiểm L2                                                       | INSURANCE_L2                                    | 8500                               |
| Bảo hiểm phi nhân thọ L3                                          | NONLIFE_INSURANCE_L3                            | 8530                               |
| Bảo hiểm phức hợp L4                                              | FULL_LINE_INSURANCE_L4                          | 8532                               |
| Môi giới bảo hiểm L4                                              | INSURANCE_BROKERS_L4                            | 8534                               |
| Bảo hiểm phi nhân thọ L4                                          | PROPERTY_AND_CASUALTY_INSURANCE_L4              | 8536                               |
| Tái bảo hiểm L4                                                   | REINSURANCE_L4                                  | 8538                               |
| Bảo hiểm nhân thọ L3                                              | LIFE_INSURANCE_L3                               | 8570                               |
| Bảo hiểm nhân thọ L4                                              | LIFE_INSURANCE_L4                               | 8575                               |
| Bất động sản L2                                                   | REAL_ESTATE_L2                                  | 8600                               |
| Bất động sản L3                                                   | REAL_ESTATE_INVESTMENT_AND_SERVICES_L3          | 8630                               |
| Bất động sản L4                                                   | REAL_ESTATE_HOLDING_AND_DEVELOPMENT_L4          | 8633                               |
| Tư Vấn, Định giá, Môi giới Bất động sản L4                        | REAL_ESTATE_SERVICES_L4                         | 8637                               |
| Quỹ ủy thác BĐS L3                                                | REAL_ESTATE_INVESTMENT_TRUSTS_L3                | 8670                               |
| Quỹ ủy thác BĐS L4                                                | REAL_ESTATE_INVESTMENT_TRUSTS_L4                | 8677                               |
| Dịch vụ tài chính L2                                              | FINANCIAL_SERVICES_L2                           | 8700                               |
| Dịch vụ tài chính L3                                              | FINANCIAL_SERVICES_L3                           | 8770                               |
| Quản lý tài sản L4                                                | ASSET_MANAGERS_L4                               | 8771                               |
| Tài chính cá nhân L4                                              | CONSUMER_FINANCE_L4                             | 8773                               |
| Tài chính đặc biệt L4                                             | SPECIALTY_FINANCE_L4                            | 8775                               |
| Môi giới chứng khoán L4                                           | INVESTMENT_SERVICES_L4                          | 8777                               |
| Cầm cố L4                                                         | MORTGAGE_FINANCE_L4                             | 8779                               |
| Quỹ đầu tư L3                                                     | EQUITY_INVESTMENT_INSTRUMENTS_L3                | 8980                               |
| Quỹ đầu tư L4                                                     | EQUITY_INVESTMENT_INSTRUMENTS_L4                | 8985                               |
| Công nghệ Thông tin L1                                            | TECHNOLOGY_L1                                   | 9000                               |
| Công nghệ Thông tin L2                                            | TECHNOLOGY_L2                                   | 9500                               |
| Phần mềm & Dịch vụ Máy tính L3                                    | SOFTWARE_AND_COMPUTER_SERVICES_L3               | 9530                               |
| Dịch vụ Máy tính L4                                               | COMPUTER_SERVICES_L4                            | 9533                               |
| Internet L4                                                       | INTERNET_L4                                     | 9535                               |
| Phần mềm L4                                                       | SOFTWARE_L4                                     | 9537                               |
| Thiết bị và Phần cứng L3                                          | TECHNOLOGY_HARDWARE_AND_EQUIPMENT_L3            | 9570                               |
| Phần cứng L4                                                      | COMPUTER_HARDWARE_L4                            | 9572                               |
| Thiết bị văn phòng L4                                             | ELECTRONIC_OFFICE_EQUIPMENT_L4                  | 9574                               |
| Bán dẫn L4                                                        | SEMICONDUCTORS_L4                               | 9576                               |
| Thiết bị viễn thông L4                                            | TELECOMMUNICATIONS_EQUIPMENT_L4                 | 9578                               |
| N/A L4 L4                                                         | N/A_L4_L4                                       | OTHER                              |
| Sản xuất và Khai thác dầu khí L5                                  | EXPLORATION_AND_PRODUCTION_L5                   | 05331                              |
| Tổ hợp Dầu khí L5                                                 | INTEGRATED_OIL_AND_GAS_L5                       | 05371                              |
| Thiết bị và Dịch vụ Dầu khí L5                                    | OIL_EQUIPMENT_AND_SERVICES_L5                   | 05731                              |
| Ống dẫn Dầu L5                                                    | PIPELINES_L5                                    | 05771                              |
| Năng lượng thay thế L3                                            | ALTERNATIVE_FUELS_L3                            | 0580                               |
| Thiết bị năng lượng tái chế L4                                    | RENEWABLE_ENERGY_EQUIPMENT_L4                   | 0583                               |
| Thiết bị năng lượng tái chế L5                                    | RENEWABLE_ENERGY_EQUIPMENT_L5                   | 05831                              |
| Nhiên liệu thay thế L4                                            | ALTERNATIVE_FUELS_L4                            | 0587                               |
| Nhiên liệu thay thế L5                                            | ALTERNATIVE_FUELS_L5                            | 05871                              |
| Nhựa L5                                                           | PLASTICS_L5                                     | 13531                              |
| Cao su L5                                                         | RUBBER_L5                                       | 13532                              |
| Sợi tổng hợp L5                                                   | SYNTHETIC_FIBERS_L5                             | 13533                              |
| Hóa chất cơ bản bán buôn L5                                       | COMMODITY_CHEMICALS_WHOLESALE_L5                | 13534                              |
| Hóa chất hàng hóa khác L5                                         | OTHER_COMMODITY_CHEMICALS_L5                    | 13571                              |
| Phân bón L5                                                       | FERTILIZER_L5                                   | 13572                              |
| Thuốc trừ sâu L5                                                  | PESTICIDE_L5                                    | 13573                              |
| Hóa chất nông nghiệp Bán buôn L5                                  | AGRICULTURAL_CHEMICALS_WHOLESALE_L5             | 13574                              |
| Lâm sản và Chế biến gỗ L5                                         | FORESTRY_L5                                     | 17331                              |
| Sản xuất giấy L5                                                  | PAPER_L5                                        | 17371                              |
| Nhôm L5                                                           | ALUMINUM_L5                                     | 17531                              |
| Kim Loại màu L5                                                   | NONFERROUS_METALS_L5                            | 17551                              |
| Sản xuất, chế biến thép L5                                        | PRODUCERS_L5                                    | 17571                              |
| Thương mại (Bán buôn) sắt thép L5                                 | METAL_MERCHANT_WHOLESALERS_L5                   | 17572                              |
| Khai thác Than L5                                                 | COAL_L5                                         | 17711                              |
| Đá quý và Kim cương L5                                            | DIAMONDS_AND_GEMSTONES_L5                       | 17731                              |
| Khai khoáng L5                                                    | GENERAL_MINING_L5                               | 17751                              |
| Khai thác vàng L5                                                 | GOLD_MINING_L5                                  | 17771                              |
| Bạch kim & Kim loại quý khác L5                                   | PLATINUM_AND_PRECIOUS_METALS_L5                 | 17791                              |
| Vật liệu xây dựng khác L5                                         | OTHER_CONSTRUCTION_MATERIALS_L5                 | 23531                              |
| Xi măng L5                                                        | CEMENT_L5                                       | 23532                              |
| Sản xuất bê tông L5                                               | CONCRET_MANUFACTURING_L5                        | 23533                              |
| Sản xuất gạch L5                                                  | BRICK_MANUFACTURING_L5                          | 23534                              |
| Sản xuất gạch ốp lát & Vật liệu lát L5                            | TILE_AND_PAVING_MATERIAL_MANUFACTURING_L5       | 23535                              |
| Khai thác đá L5                                                   | ROCK_MINING_L5                                  | 23536                              |
| Sơn và chất phủ L5                                                | PAINT_L5                                        | 23537                              |
| Vật liệu xây dựng bán buôn L5                                     | CONSTRUCTION_MATERIAL_WHOLESALE_L5              | 23538                              |
| Xây dựng L5                                                       | HEAVY_CONSTRUCTION_L5                           | 23571                              |
| Hàng không L5                                                     | AEROSPACE_L5                                    | 27131                              |
| Quốc phòng L5                                                     | DEFENSE_L5                                      | 27171                              |
| Thùng chứa và bao bì khác L5                                      | OTHER_CONTAINERS_AND_PACKAGING_L5               | 27231                              |
| Bao bì, đóng gói thủy tinh L5                                     | GLASS_CONTAINERS_AND_PACKAGING_L5               | 27232                              |
| Bao bì, đóng gói kim loại L5                                      | METAL_CONTAINERS_AND_PACKAGING_L5               | 27233                              |
| Bao bì, đóng gói bằng nhựa L5                                     | PLASTIC_CONTAINERS_AND_PACKAGING_L5             | 27234                              |
| Bao bì, đóng gói từ gỗ L5                                         | WOOD_CONTAINER_AND_PACKAGING_L5                 | 27235                              |
| Bao bì, đóng gói từ giấy L5                                       | PAPER_PACKAGING_L5                              | 27236                              |
| Vật liệu bao bì, đóng gói bán buôn L5                             | CONTAINER_AND_PACKAGING_MATERIAL_WHOLESALE_L5   | 27237                              |
| Công nghiệp phức hợp L5                                           | DIVERSIFIED_INDUSTRIALS_L5                      | 27271                              |
| Hàng điện & điện tử L5                                            | ELECTRICAL_COMPONENTS_AND_EQUIPMENT_L5          | 27331                              |
| Thiết bị điện L5                                                  | ELECTRONIC_EQUIPMENT_L5                         | 27371                              |
| Xe tải & Đóng tàu L5                                              | COMMERCIAL_VEHICLES_AND_TRUCKS_L5               | 27531                              |
| Máy công nghiệp L5                                                | INDUSTRIAL_MACHINERY_L5                         | 27571                              |
| Chuyển phát nhanh L5                                              | DELIVERY_SERVICES_L5                            | 27711                              |
| Vận tải nội địa L5                                                | INLAND_WATER_FREIGHT_L5                         | 27731                              |
| Vận tải quốc tế L5                                                | DEEP_SEA_FREIGHT_L5                             | 27732                              |
| Đường sắt L5                                                      | RAILROADS_L5                                    | 27751                              |
| Cảng hàng không L5                                                | AIRPORT_L5                                      | 27771                              |
| Bến xe khách L5                                                   | BUS/_CAR_STATION_L5                             | 27772                              |
| Dịch vụ Sân bay L5                                                | AIRPORT_SERVICES_L5                             | 27773                              |
| Dịch vụ cảng biển, cảng sông L5                                   | MARINE_PORT_SERVICES_L5                         | 27774                              |
| Dịch vụ kho bãi L5                                                | LOGISTICS_L5                                    | 27775                              |
| Hỗ trợ vận tải L5                                                 | SUPPORT_ACTIVITIES_FOR_TRANSPORTATION_L5        | 27776                              |
| Vận tải hàng lạnh L5                                              | COLD_TRUCKING_L5                                | 27791                              |
| Vận tải hàng khô L5                                               | DRY_TRUCKING_L5                                 | 27792                              |
| Tư vấn & Hỗ trợ KD L5                                             | BUSINESS_SUPPORT_SERVICES_L5                    | 27911                              |
| Đào tạo & Việc làm L5                                             | BUSINESS_TRAINING_AND_EMPLOYMENT_AGENCIES_L5    | 27933                              |
| Quản lý Tài chính L5                                              | FINANCIAL_ADMINISTRATION_L5                     | 27951                              |
| Nhà cung cấp thiết bị L5                                          | INDUSTRIAL_SUPPLIERS_L5                         | 27971                              |
| Chất thải & Môi trường L5                                         | WASTE_AND_DISPOSAL_SERVICES_L5                  | 27991                              |
| Sản xuất ô tô L5                                                  | AUTOMOBILES_L5                                  | 33531                              |
| Phụ tùng ô tô L5                                                  | AUTO_PARTS_L5                                   | 33551                              |
| Lốp xe L5                                                         | TIRES_L5                                        | 33571                              |
| Sản xuất bia L5                                                   | BREWERS_L5                                      | 35331                              |
| Vang & Rượu mạnh L5                                               | DISTILLERS_AND_VINTNERS_L5                      | 35351                              |
| Đồ uống không cồn khác L5                                         | OTHER_NON-ALCOHOLIC_BEVERAGES_L5                | 35371                              |
| Trà L5                                                            | TEA_L5                                          | 35372                              |
| Cafe L5                                                           | COFFEE_L5                                       | 35373                              |
| Đồ uống có ga mềm L5                                              | CARBONATED_SOFT_DRINKS_L5                       | 35374                              |
| Nước ngũ cốc (đậu nành, đậu phộng, vv) L5                         | CEREALS_JUICE_L5                                | 35375                              |
| Nước trái cây L5                                                  | FRUIT_DRINKS_L5                                 | 35376                              |
| Nước đóng chai L5                                                 | BOTTLED_WATER_AND_ICE_L5                        | 35377                              |
| Nuôi trồng thủy hải sản L5                                        | FISHING_L5                                      | 35731                              |
| Chăn nuôi gia súc, gia cầm L5                                     | PIG_BEEF_AND_VEAL_FARMING_L5                    | 35732                              |
| Trồng ngũ cốc, rau, trái cây & hạt L5                             | GRAIN_(CROP)_VEGETABLE_FRUIT_AND_NUT_FARMING_L5 | 35733                              |
| Hạt, cây giống thương mại L5                                      | COMMERCIAL_NURSERIES_L5                         | 35734                              |
| Trồng Cà phê, trà, ca cao L5                                      | COFFEE_TEA_AND_COCOA_FARMING_L5                 | 35735                              |
| Trồng mía L5                                                      | SUGARCANE_FARMING_L5                            | 35736                              |
| Thức ăn gia súc L5                                                | ANIMAL_FEED_L5                                  | 35737                              |
| Bán buôn, thu mua nông thủy sản L5                                | FISHING_AND_FARMING_WHOLESALE_L5                | 35738                              |
| Nông trại và nuôi trồng khác L5                                   | OTHER_FISHING_AND_FARMING_L5                    | 35739                              |
| Sô cô la, Bánh kẹo, bánh mỳ L5                                    | BREAD_CRACKER_OR_CHOCOLATE_CONFECTIONERY_L5     | 35771                              |
| Suất ăn công nghiệp L5                                            | READY_MADE_MEALS_L5                             | 357710                             |
| Thực phẩm khác L5                                                 | OTHER_FOOD_L5                                   | 357711                             |
| Trái cây và rau quả chế biến L5                                   | FRUIT_AND_VEGETABLE_PROCESSING_L5               | 35772                              |
| Động vật giết mổ và chế biến L5                                   | ANIMAL_SLAUGHTERING_AND_PROCESSING_L5           | 35773                              |
| Hải sản chế biến và đóng gói L5                                   | SEAFOOD_PRODUCT_PREPARATION_AND_PACKAGING_L5    | 35774                              |
| Thực phẩm chế biến L5                                             | PROCESSED_FOOD_L5                               | 35775                              |
| Sản phẩm từ sữa L5                                                | DAIRY_PRODUCTS_L5                               | 35776                              |
| Tinh bột, rau có chất béo L5                                      | STARCH_VEGETABLE_FAT_L5                         | 35777                              |
| Đường L5                                                          | SUGAR_L5                                        | 35778                              |
| Nguyên liệu chế biến, dầu ăn, gia vị (bột nở, hương liệu, etc) L5 | FOOD_INGREDIENT_SPICES_L5                       | 35779                              |
| Đồ gia dụng lâu bền L5                                            | DURABLE_HOUSEHOLD_PRODUCTS_L5                   | 37221                              |
| Đồ gia dụng một lần L5                                            | NONDURABLE_HOUSEHOLD_PRODUCTS_L5                | 37241                              |
| Thiết bị gia dụng L5                                              | FURNISHINGS_L5                                  | 37261                              |
| Xây nhà L5                                                        | HOME_CONSTRUCTION_L5                            | 37281                              |
| Điện tử tiêu dùng L5                                              | CONSUMER_ELECTRONICS_L5                         | 37431                              |
| Sản phẩm nghệ thuật L5                                            | RECREATIONAL_PRODUCTS_L5                        | 37451                              |
| Đồ chơi L5                                                        | TOYS_L5                                         | 37471                              |
| Hàng May mặc L5                                                   | CLOTHING_AND_ACCESSORIES_L5                     | 37631                              |
| Giầy dép L5                                                       | FOOTWEAR_L5                                     | 37651                              |
| Hàng cá nhân L5                                                   | PERSONAL_PRODUCTS_L5                            | 37671                              |
| Thuốc lá L5                                                       | TOBACCO_L5                                      | 37851                              |
| Chăm sóc y tế L5                                                  | HEALTH_CARE_PROVIDERS_L5                        | 45331                              |
| Thiết bị y tế L5                                                  | MEDICAL_EQUIPMENT_L5                            | 45351                              |
| Dụng cụ y tế L5                                                   | MEDICAL_SUPPLIES_L5                             | 45371                              |
| Công nghệ sinh học L5                                             | BIOTECHNOLOGY_L5                                | 45731                              |
| Dược phẩm L5                                                      | PHARMACEUTICALS_L5                              | 45771                              |
| Phân phối dược phẩm L5                                            | DRUG_RETAILERS_L5                               | 53331                              |
| Phân phối thực phẩm L5                                            | FOOD_RETAILERS_AND_WHOLESALERS_L5               | 53371                              |
| Bán lẻ hàng may mặc L5                                            | APPAREL_RETAILERS_L5                            | 53711                              |
| Siêu thị L5                                                       | SUPERMARKET_L5                                  | 53731                              |
| Cửa hàng tiện dụng L5                                             | CONVENIENCE_STORES_L5                           | 53732                              |
| Đại siêu thị L5                                                   | HYPERMARKET_L5                                  | 53733                              |
| Online L5                                                         | ONLINE_L5                                       | 53734                              |
| Các dịch vụ kinh doanh bán lẻ khác L5                             | OTHER_RETAILERS_L5                              | 53735                              |
| Phân phối nội thất L5                                             | HOME_IMPROVEMENT_RETAILERS_L5                   | 53751                              |
| Dịch vụ tiêu dùng chuyên ngành L5                                 | SPECIALIZED_CONSUMER_SERVICES_L5                | 53771                              |
| Phân phối hàng chuyên dụng L5                                     | SPECIALTY_RETAILERS_L5                          | 53791                              |
| Giải trí & Truyền thông L5                                        | BROADCASTING_AND_ENTERTAINMENT_L5               | 55531                              |
| Dịch vụ truyền thông L5                                           | MEDIA_AGENCIES_L5                               | 55551                              |
| Sách, ấn bản & sản phẩm văn hóa L5                                | PUBLISHING_L5                                   | 55571                              |
| Dịch vụ Hàng không L5                                             | AIRLINES_L5                                     | 57511                              |
| Gambling L5                                                       | GAMBLING_L5                                     | 57521                              |
| Khách sạn, resort L5                                              | HOTELS_AND_RESORTS_L5                           | 57531                              |
| Dịch vụ giải trí L5                                               | RECREATIONAL_SERVICES_L5                        | 57551                              |
| Nhà hàng và quán bar L5                                           | RESTAURANTS_AND_BARS_L5                         | 57571                              |
| Vận tải hành khách đường bộ L5                                    | ROAD_PASSENGER_TRANSPORT_L5                     | 57591                              |
| Vận tải hành khách đường thủy L5                                  | MARINE_PASSENGER_L5                             | 57592                              |
| Công ty du lịch L5                                                | TOURISM_L5                                      | 57593                              |
| Viễn thông cố định L5                                             | FIXED_LINE_TELECOMMUNICATIONS_L5                | 65351                              |
| Viễn thông di động L5                                             | MOBILE_TELECOMMUNICATIONS_L5                    | 65751                              |
| Sản xuất & Phân phối Điện L5                                      | CONVENTIONAL_ELECTRICITY_L5                     | 75351                              |
| Phân phối xăng dầu & khí đốt L5                                   | GAS_DISTRIBUTION_L5                             | 75731                              |
| Tiện ích khác L5                                                  | MULTIUTILITIES_L5                               | 75751                              |
| Nước L5                                                           | WATER_L5                                        | 75771                              |
| Ngân hàng thương mại truyền thống L5                              | TRADITIONAL_COMMERCIAL_BANKS_L5                 | 83551                              |
| Fin tech L5                                                       | FIN_TECH_L5                                     | 83552                              |
| Bảo hiểm phức hợp L5                                              | FULL_LINE_INSURANCE_L5                          | 85321                              |
| Môi giới bảo hiểm L5                                              | INSURANCE_BROKERS_L5                            | 85341                              |
| Bảo hiểm phi nhân thọ L5                                          | PROPERTY_AND_CASUALTY_INSURANCE_L5              | 85361                              |
| Tái bảo hiểm L5                                                   | REINSURANCE_L5                                  | 85381                              |
| Bảo hiểm nhân thọ L5                                              | LIFE_INSURANCE_L5                               | 85751                              |
| Phát triển & vận hành Bất động sản khác L5                        | OTHER_REAL_ESTATE_DEVELOPMENT_AND_OPERATIONS_L5 | 86331                              |
| Văn phòng cho thuê L5                                             | OFFICE_REAL_ESTATE_DEVELOPMENT_L5               | 86332                              |
| Bất động sản công nghiệp L5                                       | INDUSTRIAL_REAL_ESTATE_DEVELOPMENT_L5           | 86333                              |
| Bất động sản dân cư L5                                            | RESIDENTIAL_REAL_ESTATE_DEVELOPMENT_L5          | 86334                              |
| Dịch vụ Bất động sản khác L5                                      | OTHER_REAL_ESTATE_SERVICES_L5                   | 86371                              |
| Dịch vụ Bất động sản thương mại L5                                | OFFICE_REAL_ESTATE_SERVICES_L5                  | 86372                              |
| Dịch vụ Bất động sản bán lẻ L5                                    | RETAIL_REAL_ESTATE_SERVICES_L5                  | 86373                              |
| Dịch vụ Bất động sản Công nghiệp L5                               | INDUSTRIAL_REAL_ESTATE_SERVICES_L5              | 86374                              |
| Dịch vụ Bất động sản dân cư L5                                    | RESIDENTIAL_REAL_ESTATE_SERVICES_L5             | 86375                              |
| Quỹ ủy thác BĐS L5                                                | REAL_ESTATE_INVESTMENT_TRUSTS_L5                | 86771                              |
| Quản lý tài sản L5                                                | ASSET_MANAGERS_L5                               | 87711                              |
| Tài chính cá nhân L5                                              | CONSUMER_FINANCE_L5                             | 87731                              |
| Tài chính đặc biệt L5                                             | SPECIALTY_FINANCE_L5                            | 87751                              |
| Môi giới chứng khoán L5                                           | INVESTMENT_SERVICES_L5                          | 87771                              |
| Cầm cố L5                                                         | MORTGAGE_FINANCE_L5                             | 87791                              |
| Quỹ đầu tư L5                                                     | EQUITY_INVESTMENT_INSTRUMENTS_L5                | 89851                              |
| Dịch vụ Máy tính L5                                               | COMPUTER_SERVICES_L5                            | 95331                              |
| Internet L5                                                       | INTERNET_L5                                     | 95351                              |
| Phần mềm L5                                                       | SOFTWARE_L5                                     | 95371                              |
| Phần cứng L5                                                      | COMPUTER_HARDWARE_L5                            | 95721                              |
| Thiết bị văn phòng L5                                             | ELECTRONIC_OFFICE_EQUIPMENT_L5                  | 95741                              |
| Bán dẫn L5                                                        | SEMICONDUCTORS_L5                               | 95761                              |
| Thiết bị viễn thông L5                                            | TELECOMMUNICATIONS_EQUIPMENT_L5                 | 95781                              |
| N/A L5 L5                                                         | N/A_L5_L5                                       | OTHER5                             |
| N/A L1 L1                                                         | N/A_L1_L1                                       | OTHER1                             |
| N/A L2 L2                                                         | N/A_L2_L2                                       | OTHER2                             |
| N/A L3 L3                                                         | N/A_L3_L3                                       | OTHER3                             |
```


# 1.3. Danh sách mã theo tỷ trọng

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Bằng cách nhập vào tên INDEX (Ví dụ: VN30, VN100, VNINDEX, HNXINDEX, v.v.), số ngày ảnh hưởng(1 ngày, 5 ngày, 10 ngày, 20 ngày), loại hình ảnh hưởng (đóng góp tăng mạnh nhất hoặc đóng góp giảm mạnh nhất) và top ảnh hưởng hàm sẽ trả ra 1 bảng chứa thông tin danh sách các mã có ảnh hưởng mạnh tới INDEX đó theo chiều hướng tăng điểm hoặc giảm điểm trong vòng số ngày tùy người dùng chọn đi kèm với số điểm đóng góp và tỷ trọng đóng góp, số lượng mã sẽ tùy người dùng chọn.

Code mẫu:

```python
from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

data = client.MoneyFlow().get_contribution(
    ticker="VNINDEX",
    contribution_day="20Day",
    type="topGainers",
    top=15
)
print(data)
```

**Tham số**

| Tên tham số       | Mô tả                                                   | Kiểu dữ liệu | Mặc định | Bắt buộc |
| ----------------- | ------------------------------------------------------- | ------------ | -------- | -------- |
| ticker            | tên INDEX (Ví dụ: VN30, VN100, VNINDEX, HNXINDEX, v.v.) | str          |          | Có       |
| contribution\_day | Số ngày đóng góp (1 ngày, 5 ngày, 10 ngày, 20 ngày)     | str          |          | Có       |
| type              | kiểu top (top tăng điểm, top giảm điểm)                 | str          |          | Có       |
| top               | Số lượng mã trả ra                                      | int          | 15       | Không    |

Dữ liệu có các thuộc tính:

| Tên thuộc tính      | Mô tả                                        | Kiểu dữ liệu |
| ------------------- | -------------------------------------------- | ------------ |
| ticker              | Tên mã.                                      | str          |
| rank                | Xếp hạng.                                    | int          |
| contribution        | Số điểm đóng góp cho chỉ số được chọn        | float        |
| contributionPercent | Phần trăm điểm đóng góp cho chỉ số được chọn | float        |


# 1.4. Lấy dữ liệu vốn hóa

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.PriceStatistics().get_overview(
    tickers=tickers,
    time_filter=time_filter,
    from_date=from_date,
    to_date=to_date
)
```

**Tham số:**

<table><thead><tr><th>Tên tham số</th><th width="149">Mô tả</th><th>Kiểu dữ liệu</th><th>Mặc định</th><th>Bắt buộc</th></tr></thead><tbody><tr><td>tickers</td><td>Danh sách mã được viết in hoa.</td><td>str hoặc list</td><td></td><td>Có</td></tr><tr><td>time_filter</td><td>Tần suất lấy dữ liệu, có thể lấy dữ liệu theo Ngày, Tuần, Tháng, Quý, Năm. Truyền vào 1 trong 5 giá trị "Daily", "Weekly", "Monthly", "Quarterly", "Yearly".</td><td>str</td><td></td><td>Có</td></tr><tr><td>from_date</td><td>Mốc thời gian lấy dữ liệu xa nhất.</td><td>str</td><td></td><td>Có</td></tr><tr><td>to_date</td><td>Mốc thời gian lấy dữ liệu gần nhất.</td><td>str</td><td>datetime.now()</td><td>Không</td></tr></tbody></table>

Class nhận dữ liệu là PriceStatistics và có phương thức nhận dữ liệu là get\_Overview()

```python
data = client.PriceStatistics().get_overview(
    tickers=tickers,
    time_filter="Daily",
    from_date="2025-08-20",
    to_date="2025-08-27"
)
print(data)
```

Dữ liệu có các thuộc tính:

* time\_filter="Daily"

| Tên thuộc tính     | Mô tả                                         | Kiểu dữ liệu |
| ------------------ | --------------------------------------------- | ------------ |
| ticker             | Tên mã.                                       | str          |
| timestamp          | Thời gian giao dịch                           | str          |
| percentPriceChange | % thay đổi giá đóng cửa so với giá tham chiếu | float        |
| totalMatchVolume   | Tổng khối lượng khớp lệnh                     | float        |
| totalMatchValue    | Tổng giá trị khớp lệnh                        | int          |
| totalDealVolume    | Tổng khối lượng thỏa thuận                    | float        |
| totalDealValue     | Tổng giá trị thỏa thuận                       | int          |
| marketCap          | Tổng giá trị vốn hóa                          | int          |

* time\_filter="Weekly"

| Tên thuộc tính     | Mô tả                      | Kiểu dữ liệu |
| ------------------ | -------------------------- | ------------ |
| ticker             | Tên mã.                    | str          |
| week               | Tuần trong năm             | int          |
| year               | Năm                        | int          |
| totalMatchVolume   | Tổng khối lượng khớp lệnh  | float        |
| totalMatchValue    | Tổng giá trị khớp lệnh     | int          |
| totalDealVolume    | Tổng khối lượng thỏa thuận | float        |
| totalDealValue     | Tổng giá trị thỏa thuận    | int          |
| percentPriceChange | % thay đổi giá đóng cửa 1W | float        |
| marketCap          | Tổng giá trị vốn hóa       | int          |

* time\_filter="Monthly"

| Tên thuộc tính     | Mô tả                      | Kiểu dữ liệu |
| ------------------ | -------------------------- | ------------ |
| ticker             | Tên mã.                    | str          |
| month              | Tháng trong năm            | int          |
| year               | Năm                        | int          |
| totalMatchVolume   | Tổng khối lượng khớp lệnh  | float        |
| totalMatchValue    | Tổng giá trị khớp lệnh     | int          |
| totalDealVolume    | Tổng khối lượng thỏa thuận | float        |
| totalDealValue     | Tổng giá trị thỏa thuận    | int          |
| percentPriceChange | % thay đổi giá đóng cửa 1M | float        |
| marketCap          | Tổng giá trị vốn hóa       | int          |

* time\_filter="Quarterly"

| Tên thuộc tính     | Mô tả                      | Kiểu dữ liệu |
| ------------------ | -------------------------- | ------------ |
| ticker             | Tên mã.                    | str          |
| quarter            | Quý trong năm              | int          |
| year               | Năm                        | int          |
| totalMatchVolume   | Tổng khối lượng khớp lệnh  | float        |
| totalMatchValue    | Tổng giá trị khớp lệnh     | int          |
| totalDealVolume    | Tổng khối lượng thỏa thuận | float        |
| totalDealValue     | Tổng giá trị thỏa thuận    | int          |
| percentPriceChange | % thay đổi giá đóng cửa 1Q | float        |
| marketCap          | Tổng giá trị vốn hóa       | int          |

* time\_filter="Yearly"

| Tên thuộc tính     | Mô tả                      | Kiểu dữ liệu |
| ------------------ | -------------------------- | ------------ |
| ticker             | Tên mã.                    | str          |
| year               | Năm                        | int          |
| totalMatchVolume   | Tổng khối lượng khớp lệnh  | float        |
| totalMatchValue    | Tổng giá trị khớp lệnh     | int          |
| totalDealVolume    | Tổng khối lượng thỏa thuận | float        |
| totalDealValue     | Tổng giá trị thỏa thuận    | int          |
| percentPriceChange | % thay đổi giá đóng cửa 1Y | float        |
| marketCap          | Tổng giá trị vốn hóa       | int          |

Ví dụ:

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ["HPG", "MWG"]

data = client.PriceStatistics().get_overview(
    tickers=tickers,
    time_filter="Daily",
    from_date="2025-08-20",
    to_date="2025-08-27"
)
print(data)
```


# 1.5. Lấy dữ liệu room NĐTNN

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```
data = client.PriceStatistics().get_foreign(
    tickers=tickers,
    time_filter=time_filter,
    from_date=from_date,
    to_date=to_date
).get_data()
```

**Tham số:**

| Tên tham số  | Mô tả                                                                                                                                                        | Kiểu dữ liệu  | Mặc định       | Bắt buộc |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- | -------------- | -------- |
| tickers      | Danh sách mã được viết in hoa.                                                                                                                               | str hoặc list |                | Có       |
| time\_filter | Tần suất lấy dữ liệu, có thể lấy dữ liệu theo Ngày, Tuần, Tháng, Quý, Năm. Truyền vào 1 trong 5 giá trị "Daily", "Weekly", "Monthly", "Quarterly", "Yearly". | str           |                | Có       |
| from\_date   | Mốc thời gian lấy dữ liệu xa nhất.                                                                                                                           | str           |                | Có       |
| to\_date     | Mốc thời gian lấy dữ liệu gần nhất.                                                                                                                          | str           | datetime.now() | Không    |

Class nhận dữ liệu là PriceStatistics và có phương thức nhận dữ liệu là get\_foreign()

```python
data = client.PriceStatistics().get_foreign(
    tickers=tickers,
    time_filter="Daily",
    from_date="2025-08-20",
    to_date="2025-08-27"
)
print(data)
```

Dữ liệu có các thuộc tính:

* time\_filter="Daily"

| Tên thuộc tính           | Mô tả                           | Kiểu dữ liệu |
| ------------------------ | ------------------------------- | ------------ |
| ticker                   | Tên mã.                         | str          |
| timestamp                | Thời gian giao dịch             | str          |
| foreignBuyVolumeTotal    | Khối lượng NĐTNN mua vào        | float        |
| foreignSellVolumeTotal   | Khối lượng NĐTNN bán ra         | float        |
| foreignBuyValueTotal     | Giá trị NĐTNN mua vào           | int          |
| foreignSellValueTotal    | Giá trị NĐTNN bán ra            | int          |
| foreignNetVolumeTotal    | Khối lượng NĐTNN mua/bán ròng   | float        |
| foreignNetValueTotal     | Giá trị NĐTNN mua/bán ròng      | int          |
| foreignBuyVolumeMatched  | Khối lượng NĐTNN mua khớp lệnh  | float        |
| foreignSellVolumeMatched | Khối lượng NĐTNN bán khớp lệnh  | float        |
| foreignBuyValueMatched   | Giá trị NĐTNN mua khớp lệnh     | int          |
| foreignSellValueMatched  | Giá trị NĐTNN bán khớp lệnh     | int          |
| foreignBuyVolumeDeal     | Khối lượng NĐTNN mua thỏa thuận | float        |
| foreignSellVolumeDeal    | Khối lượng NĐTNN bán thỏa thuận | float        |
| foreignBuyValueDeal      | Giá trị NĐTNN mua thỏa thuận    | int          |
| foreignSellValueDeal     | Giá trị NĐTNN bán thỏa thuận    | int          |
| foreignCurrentRoom       | Giá trị room hiện hại của NĐTNN | int          |
| foreignTotalRoom         | Giá trị room tối đa của NĐTNN   | int          |
| percentForeignTotalRoom  | % room hiện tại của NĐTNN       | float        |
| foreignOwned             | Giá trị sở hữu của NĐTNN        | int          |
| percentForeignOwned      | % sở hữu của NĐTNN              | float        |

* time\_filter="Weekly"

| Tên thuộc tính           | Mô tả                           | Kiểu dữ liệu |
| ------------------------ | ------------------------------- | ------------ |
| ticker                   | Tên mã.                         | str          |
| week                     | Tuần trong năm                  | int          |
| year                     | Năm                             | int          |
| foreignBuyVolumeTotal    | Khối lượng NĐTNN mua vào        | float        |
| foreignSellVolumeTotal   | Khối lượng NĐTNN bán ra         | float        |
| foreignBuyValueTotal     | Giá trị NĐTNN mua vào           | int          |
| foreignSellValueTotal    | Giá trị NĐTNN bán ra            | int          |
| foreignNetVolumeTotal    | Khối lượng NĐTNN mua/bán ròng   | float        |
| foreignNetValueTotal     | Giá trị NĐTNN mua/bán ròng      | int          |
| foreignBuyVolumeMatched  | Khối lượng NĐTNN mua khớp lệnh  | float        |
| foreignSellVolumeMatched | Khối lượng NĐTNN bán khớp lệnh  | float        |
| foreignBuyValueMatched   | Giá trị NĐTNN mua khớp lệnh     | int          |
| foreignSellValueMatched  | Giá trị NĐTNN bán khớp lệnh     | int          |
| foreignBuyVolumeDeal     | Khối lượng NĐTNN mua thỏa thuận | float        |
| foreignSellVolumeDeal    | Khối lượng NĐTNN bán thỏa thuận | float        |
| foreignBuyValueDeal      | Giá trị NĐTNN mua thỏa thuận    | int          |
| foreignSellValueDeal     | Giá trị NĐTNN bán thỏa thuận    | int          |
| foreignCurrentRoom       | Giá trị room hiện hại của NĐTNN | int          |
| foreignTotalRoom         | Giá trị room tối đa của NĐTNN   | int          |
| percentForeignTotalRoom  | % room hiện tại của NĐTNN       | float        |
| foreignOwned             | Giá trị sở hữu của NĐTNN        | int          |
| percentForeignOwned      | % sở hữu của NĐTNN              | float        |

* time\_filter="Monthly"

| Tên thuộc tính           | Mô tả                           | Kiểu dữ liệu |
| ------------------------ | ------------------------------- | ------------ |
| ticker                   | Tên mã.                         | str          |
| month                    | Tháng trong năm                 | int          |
| year                     | Năm                             | int          |
| foreignBuyVolumeTotal    | Khối lượng NĐTNN mua vào        | float        |
| foreignSellVolumeTotal   | Khối lượng NĐTNN bán ra         | float        |
| foreignBuyValueTotal     | Giá trị NĐTNN mua vào           | int          |
| foreignSellValueTotal    | Giá trị NĐTNN bán ra            | int          |
| foreignNetVolumeTotal    | Khối lượng NĐTNN mua/bán ròng   | float        |
| foreignNetValueTotal     | Giá trị NĐTNN mua/bán ròng      | int          |
| foreignBuyVolumeMatched  | Khối lượng NĐTNN mua khớp lệnh  | float        |
| foreignSellVolumeMatched | Khối lượng NĐTNN bán khớp lệnh  | float        |
| foreignBuyValueMatched   | Giá trị NĐTNN mua khớp lệnh     | int          |
| foreignSellValueMatched  | Giá trị NĐTNN bán khớp lệnh     | int          |
| foreignBuyVolumeDeal     | Khối lượng NĐTNN mua thỏa thuận | float        |
| foreignSellVolumeDeal    | Khối lượng NĐTNN bán thỏa thuận | float        |
| foreignBuyValueDeal      | Giá trị NĐTNN mua thỏa thuận    | int          |
| foreignSellValueDeal     | Giá trị NĐTNN bán thỏa thuận    | int          |
| foreignCurrentRoom       | Giá trị room hiện hại của NĐTNN | int          |
| foreignTotalRoom         | Giá trị room tối đa của NĐTNN   | int          |
| percentForeignTotalRoom  | % room hiện tại của NĐTNN       | float        |
| foreignOwned             | Giá trị sở hữu của NĐTNN        | int          |
| percentForeignOwned      | % sở hữu của NĐTNN              | float        |

* time\_filter="Quarterly"

| Tên thuộc tính           | Mô tả                           | Kiểu dữ liệu |
| ------------------------ | ------------------------------- | ------------ |
| ticker                   | Tên mã.                         | str          |
| quarter                  | Quý trong năm                   | int          |
| year                     | Năm                             | int          |
| foreignBuyVolumeTotal    | Khối lượng NĐTNN mua vào        | float        |
| foreignSellVolumeTotal   | Khối lượng NĐTNN bán ra         | float        |
| foreignBuyValueTotal     | Giá trị NĐTNN mua vào           | int          |
| foreignSellValueTotal    | Giá trị NĐTNN bán ra            | int          |
| foreignNetVolumeTotal    | Khối lượng NĐTNN mua/bán ròng   | float        |
| foreignNetValueTotal     | Giá trị NĐTNN mua/bán ròng      | int          |
| foreignBuyVolumeMatched  | Khối lượng NĐTNN mua khớp lệnh  | float        |
| foreignSellVolumeMatched | Khối lượng NĐTNN bán khớp lệnh  | float        |
| foreignBuyValueMatched   | Giá trị NĐTNN mua khớp lệnh     | int          |
| foreignSellValueMatched  | Giá trị NĐTNN bán khớp lệnh     | int          |
| foreignBuyVolumeDeal     | Khối lượng NĐTNN mua thỏa thuận | float        |
| foreignSellVolumeDeal    | Khối lượng NĐTNN bán thỏa thuận | float        |
| foreignBuyValueDeal      | Giá trị NĐTNN mua thỏa thuận    | int          |
| foreignSellValueDeal     | Giá trị NĐTNN bán thỏa thuận    | int          |
| foreignCurrentRoom       | Giá trị room hiện hại của NĐTNN | int          |
| foreignTotalRoom         | Giá trị room tối đa của NĐTNN   | int          |
| percentForeignTotalRoom  | % room hiện tại của NĐTNN       | float        |
| foreignOwned             | Giá trị sở hữu của NĐTNN        | int          |
| percentForeignOwned      | % sở hữu của NĐTNN              | float        |

* time\_filter="Yearly"

| Tên thuộc tính           | Mô tả                           | Kiểu dữ liệu |
| ------------------------ | ------------------------------- | ------------ |
| ticker                   | Tên mã.                         | str          |
| year                     | Năm                             | int          |
| foreignBuyVolumeTotal    | Khối lượng NĐTNN mua vào        | float        |
| foreignSellVolumeTotal   | Khối lượng NĐTNN bán ra         | float        |
| foreignBuyValueTotal     | Giá trị NĐTNN mua vào           | int          |
| foreignSellValueTotal    | Giá trị NĐTNN bán ra            | int          |
| foreignNetVolumeTotal    | Khối lượng NĐTNN mua/bán ròng   | float        |
| foreignNetValueTotal     | Giá trị NĐTNN mua/bán ròng      | int          |
| foreignBuyVolumeMatched  | Khối lượng NĐTNN mua khớp lệnh  | float        |
| foreignSellVolumeMatched | Khối lượng NĐTNN bán khớp lệnh  | float        |
| foreignBuyValueMatched   | Giá trị NĐTNN mua khớp lệnh     | int          |
| foreignSellValueMatched  | Giá trị NĐTNN bán khớp lệnh     | int          |
| foreignBuyVolumeDeal     | Khối lượng NĐTNN mua thỏa thuận | float        |
| foreignSellVolumeDeal    | Khối lượng NĐTNN bán thỏa thuận | float        |
| foreignBuyValueDeal      | Giá trị NĐTNN mua thỏa thuận    | int          |
| foreignSellValueDeal     | Giá trị NĐTNN bán thỏa thuận    | int          |
| foreignCurrentRoom       | Giá trị room hiện hại của NĐTNN | int          |
| foreignTotalRoom         | Giá trị room tối đa của NĐTNN   | int          |
| percentForeignTotalRoom  | % room hiện tại của NĐTNN       | float        |
| foreignOwned             | Giá trị sở hữu của NĐTNN        | int          |
| percentForeignOwned      | % sở hữu của NĐTNN              | float        |

Ví dụ:

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ["HPG", "MWG"]

data = client.PriceStatistics().get_foreign(
    tickers=tickers,
    time_filter="Daily",
    from_date="2025-08-20",
    to_date="2025-08-27"
)
print(data)
```


# 1.6. Lấy dữ liệu Freefloat

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.PriceStatistics().get_freefloat(
    tickers=tickers,
    from_date=from_date,
    to_date=to_date
).get_data()
```

**Tham số:**

| Tên tham số | Mô tả                               | Kiểu dữ liệu  | Mặc định | Bắt buộc |
| ----------- | ----------------------------------- | ------------- | -------- | -------- |
| tickers     | Danh sách mã được viết in hoa.      | str hoặc list |          | Có       |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.  | str           |          | Có       |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất. | str           |          | Có       |

Class nhận dữ liệu là PriceStatistics và có phương thức nhận dữ liệu là get\_freefloat()

```python
data = client.PriceStatistics().get_freefloat(
    tickers=tickers,
    from_date="2025-08-20",
    to_date="2025-08-27"
)
print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Mô tả                                | Kiểu dữ liệu |
| -------------- | ------------------------------------ | ------------ |
| ticker         | Tên mã.                              | str          |
| timestamp      | Thời gian giao dịch                  | str          |
| freefloat      | Giá trị cổ phiếu chuyển nhượng tự do | int          |

Ví dụ:

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ["HPG", "MWG"]

data = client.PriceStatistics().get_freefloat(
    tickers=tickers,
    from_date="2025-08-20",
    to_date="2025-08-27"
)
print(data)
```


# 1.7. Lấy dữ liệu giá trần, giá sàn

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.PriceStatistics().get_ceilingfloor(
    tickers=tickers,
    from_date=from_date,
    to_date=to_date
)
```

**Tham số:**

| Tên tham số | Mô tả                               | Kiểu dữ liệu  | Mặc định       | Bắt buộc |
| ----------- | ----------------------------------- | ------------- | -------------- | -------- |
| tickers     | Danh sách mã được viết in hoa.      | str hoặc list |                | Có       |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.  | str           |                | Có       |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất. | str           | datetime.now() | Không    |

Class nhận dữ liệu là PriceStatistics và có phương thức nhận dữ liệu là get\_ceilingfloor()

```python
data = client.PriceStatistics().get_ceilingfloor(
    tickers=tickers,
    from_date="2025-10-01",
    to_date="2025-10-08"
)

print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Mô tả               | Kiểu dữ liệu |
| -------------- | ------------------- | ------------ |
| ticker         | Tên mã.             | str          |
| timestamp      | Thời gian giao dịch | str          |
| floorValue     | Giá sàn             | int          |
| ceilingValue   | Giá trần            | int          |

Ví dụ:

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ["HPG", "MWG"]

data = client.PriceStatistics().get_ceilingfloor(
    tickers=tickers,
    from_date="2025-10-01",
    to_date="2025-10-08"
)
print(data)
```


# 1.8. Lấy dữ liệu giao dịch theo nhà đầu tư

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

{% hint style="info" %}
**Lưu ý:** Từ ngày 01/09/2026, FiinQuant tạm dừng cập nhật dữ liệu giao dịch của nhà đầu tư cá nhân trong nước, tổ chức trong nước, cá nhân nước ngoài và tổ chức nước ngoài. Dữ liệu giao dịch của tự doanh vẫn cập nhật bình thường
{% endhint %}

```python
data = client.PriceStatistics().get_value_by_investor(
    tickers=tickers,
    from_date=from_date,
    to_date=to_date
)
```

**Tham số:**

| Tên tham số | Mô tả                               | Kiểu dữ liệu  | Mặc định       | Bắt buộc |
| ----------- | ----------------------------------- | ------------- | -------------- | -------- |
| tickers     | Danh sách mã được viết in hoa.      | str hoặc list |                | Có       |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.  | str           |                | Có       |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất. | str           | datetime.now() | Không    |

Class nhận dữ liệu là PriceStatistics và có phương thức nhận dữ liệu là get\_value\_by\_investor()

```python
data = client.PriceStatistics().get_value_by_investor(
    tickers=tickers,
    from_date="2025-10-01",
    to_date="2025-10-08"
)

print(data)
```

Dữ liệu có các thuộc tính:

<table><thead><tr><th width="244">Tên thuộc tính</th><th>Mô tả</th><th>Kiểu dữ liệu</th></tr></thead><tbody><tr><td>ticker</td><td>Tên mã.</td><td>str</td></tr><tr><td>timestamp</td><td>Thời gian giao dịch</td><td>str</td></tr><tr><td>localIndividualNetMatchVolume</td><td>Khối lượng cá nhân trong nước khớp ròng</td><td>int</td></tr><tr><td>foreignIndividualNetMatchVolume</td><td>Khối lượng cá nhân nước ngoài khớp ròng</td><td>int</td></tr><tr><td>localInstitutionalNetMatchVolume</td><td>Khối lượng tổ chức trong nước khớp ròng</td><td>int</td></tr><tr><td>foreignInstitutionalNetMatchVolume</td><td>Khối lượng tổ chức nước ngoài khớp ròng</td><td>int</td></tr><tr><td>localIndividualNetMatchValue</td><td>Giá trị cá nhân trong nước khớp ròng</td><td>int</td></tr><tr><td>foreignIndividualNetMatchValue</td><td>Giá trị cá nhân nước ngoài khớp ròng</td><td>int</td></tr><tr><td>localInstitutionalNetMatchValue</td><td>Giá trị tổ chức trong nước khớp ròng</td><td>int</td></tr><tr><td>foreignInstitutionalNetMatchValue</td><td>Giá trị tổ chức nước ngoài khớp ròng</td><td>int</td></tr><tr><td>proprietaryNetTotalMatchVolume</td><td>Khối lượng tự doanh khớp ròng</td><td>int</td></tr><tr><td>proprietaryNetTotalMatchValue</td><td>Giá trị tự doanh khớp ròng</td><td>int</td></tr></tbody></table>

Ví dụ:

<pre class="language-python"><code class="lang-python">from FiinQuantX import FiinSession
<strong>
</strong>username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ["HPG", "MWG"]

data = client.PriceStatistics().get_value_by_investor(
    tickers=tickers,
    from_date="2025-10-01",
    to_date="2025-10-08"
)
print(data)
</code></pre>


# 1.9. Lấy dữ liệu thông tin cơ bản của cổ phiếu (tên DN, sàn GD, ngành)

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.BasicInfor(
    tickers=tickers
).get()
```

**Tham số:**

| Tên tham số | Mô tả                          | Kiểu dữ liệu  | Mặc định | Bắt buộc |
| ----------- | ------------------------------ | ------------- | -------- | -------- |
| tickers     | Danh sách mã được viết in hoa. | str hoặc list |          | Có       |

**Code mẫu lấy thông tin cơ bản của danh sách các cổ phiếu VN30:**

```python
tickers = client.TickerList(ticker="VN30")
data = client.BasicInfor(
    tickers=tickers
).get()
print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính        | Mô tả                                | Kiểu dữ liệu |
| --------------------- | ------------------------------------ | ------------ |
| ticker                | Tên mã.                              | str          |
| taxCode               | Mã số thuế doanh nghiệp.             | str          |
| organizationName      | Tên đầy đủ doanh nghiệp.             | str          |
| organizationShortName | Tên viết tắt doanh nghiệp.           | str          |
| exchangeCode          | Tên sàn giao dịch.                   | str          |
| sector                | Tên ngành.                           | str          |
| icbNameL5             | Tên ngành cấp 5 dùng để làm tham số. | str          |
| icbNameL4             | Tên ngành cấp 4 dùng để làm tham số. | str          |
| icbNameL3             | Tên ngành cấp 3 dùng để làm tham số. | str          |
| icbNameL2             | Tên ngành cấp 2 dùng để làm tham số. | str          |
| icbNameL1             | Tên ngành cấp 1 dùng để làm tham số. | str          |


# 2. Dữ liệu giao dịch


# 2.1. Hàm dữ liệu Realtime

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
Events = client.Trading_Data_Stream(tickers = tickers, callback = callback)
```

**Tham số**

<table><thead><tr><th>Tên tham số</th><th width="187">Mô tả</th><th>Kiểu dữ liệu</th><th>Bắt buộc</th></tr></thead><tbody><tr><td>tickers</td><td>Tên mã , bao gồm mã chứng khoán, mã chỉ số, mã phái sinh và mã chứng quyền. Các mã này được viết in hoa.</td><td><p>str hoặc list</p><p><br></p></td><td>Có</td></tr><tr><td>callback</td><td>Là hàm do người dùng tự định nghĩa để thao tác với dữ liệu.</td><td>function</td><td>Có</td></tr></tbody></table>

Class nhận dữ liệu là Trading\_Data\_Stream, có 2 phương thức sau:

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F9d370Vba9Vx8mVLcNLw0%2Fimage.png?alt=media&amp;token=f871c40b-d6b5-4319-879f-02d2e24adfcd" alt=""><figcaption></figcaption></figure>

**Hàm callback**

Là phương thức do người dùng tự định nghĩa để thao tác với dữ liệu, sẽ được truyền vào khi khởi tạo đối tượng nhận dữ liệu như là một đối số. Phương thức này sẽ có dạng như sau:

```python
//pseudocode
//callback_function
def name_of_callback(data: RealTimeData):
    //do something

Events = client.Trading_Data_Stream(tickers = ['ticker_1','ticker_2',,,'ticker_n'], callback = name_of_callback)
Events.start()
# tickers can include ticker, coveredwarrant, index and derivative.
Events = client.Trading_Data_Stream(tickers = ['ticker_1','ticker_2',,,'ticker_n'], callback = name_of_callback)
Events.start()
```

RealTimeData có các phương thức và thuộc tính sau:<br>

| Tên phương thức của object dữ liệu | Mô tả                                                                                                                  |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| to\_dataFrame( )                   | Trả về tất cả các thuộc tính của dữ liệu thay vì một thuộc tính riêng lẻ, được lưu trữ dưới dạng một Pandas DataFrame. |

**Dữ liệu RealTimeData có các thuộc tính:**

| Tên cột                | Mô tả                                         | Kiểu dữ liệu |
| ---------------------- | --------------------------------------------- | ------------ |
| Ticker                 | Tên mã.                                       | str          |
| TotalMatchVolume       | Tổng khối lượng.                              | int          |
| MarketStatus           | Trạng thái thị trường.                        | str          |
| TradingDate            | Thời gian.                                    | str          |
| ComGroupCode           | Mã chỉ số.                                    | str          |
| Reference              | Giá trị tham chiếu.                           | float        |
| Open                   | Giá Open.                                     | float        |
| Close                  | Giá Close.                                    | float        |
| High                   | Giá High.                                     | float        |
| Low                    | Giá Low.                                      | float        |
| Change                 | Giá trị thay đổi so với tham chiếu.           | float        |
| ChangePercent          | Phần trăm giá trị thay đổi so với tham chiếu. | float        |
| MatchVolume            | Khối lượng khớp lệnh.                         | int          |
| MatchValue             | Giá trị khớp lệnh.                            | float        |
| TotalMatchValue        | Tổng giá trị khớp lệnh.                       | float        |
| TotalBuyTradeVolume    | Tổng khối lượng mua vào.                      | int          |
| TotalSellTradeVolume   | Tổng khối lượng bán ra.                       | int          |
| TotalDealVolume        | Tổng khối lượng khớp lệnh thỏa thuận.         | int          |
| TotalDealValue         | Tổng giá trị khớp lệnh thỏa thuận.            | float        |
| ForeignBuyVolumeTotal  | Tổng khối lượng mua ngoại từ đầu ngày.        | int          |
| ForeignBuyValueTotal   | Tổng giá trị mua ngoại từ đầu ngày.           | float        |
| ForeignSellVolumeTotal | Tổng khối lượng bán ngoại từ đầu ngày.        | int          |
| ForeignSellValueTotal  | Tổng giá trị bán ngoại từ đầu ngày.           | float        |
| Bu                     | Khối lượng mua chủ động.                      | int          |
| Sd                     | Khối lượng bán chủ động.                      | int          |

Ví dụ về dữ liệu khớp lệnh (RealTimeData):

```python
import pandas as pd
import time

from FiinQuantX import FiinSession, RealTimeData

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG','VNINDEX','VN30F1M']

def onTickerEvent(data: RealTimeData):
    print('----------------')
    print(data.to_dataFrame())
    # data.to_dataFrame().to_csv('callback.csv', mode='a', header=True)
Events = client.Trading_Data_Stream(tickers=tickers, callback = onTickerEvent)
Events.start()

try:
    while not Events._stop: 
        time.sleep(1)
except KeyboardInterrupt:
    print("KeyboardInterrupt received, stopping...")
    Events.stop()
```


# 2.2. Hàm dữ liệu Lịch sử

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.Fetch_Trading_Data(
    realtime = False, 
    tickers = tickers,
    fields = ['open', 'high', 'low', 'close', 'volume', 'value', 'bu','sd', 'fb', 'fs', 'fn'], 
    adjusted = True,
    by = by,
    period = 100,
    lasted = True
).get_data()
```

**Tham số: (Lưu ý:** period chỉ tồn tại khi không truyền from\_date và ngược lại). Và phải lựa chọn 1 trong 2 cách truyền này.

| Tên tham số | Mô tả                                                                                                                                        | Kiểu dữ liệu  | Mặc định | Bắt buộc       |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------- | -------------- |
| realtime    | Có đăng ký vào dữ liệu update liên tục hay không hay chỉ gọi dữ liệu lịch sử đến thời điểm mới nhất (True là có, False là không).            | bool          |          | Có.            |
| tickers     | Danh sách mã được viết in hoa.                                                                                                               | str hoặc list |          | Có.            |
| fields      | Các trường dữ liệu cần lấy. \['open','high','low','close','volume','bu','sd','fb','fs','fn'] ứng với Open, High, Low, Close, Volume, BU, SD. | list          |          | Có.            |
| adjusted    | Giá điều chỉnh hay chưa điều chỉnh (True là đã điều chỉnh và ngược lại).                                                                     | bool          | True     | Không.         |
| by          | Đơn vị thời gian(1m, 5m, 15m, 30m, 1h, 2h, 4h, 1d).                                                                                          | str           | 1M       | Không.         |
| period      | Số nến lịch sử gần nhất cần lấy.                                                                                                             | int           |          | Không.         |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.                                                                                                           | str           | datetime |                |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất.                                                                                                          | str           | datetime | datetime.now() |
| lasted      | Có lấy dữ liệu nến mới nhất chưa đóng hay không                                                                                              | bool          | False    | Không.         |

Class nhận dữ liệu là Fetch\_Trading\_Data và 2 phương thức sau:

| Tên phương thức | Mô tả                                                                                              |
| --------------- | -------------------------------------------------------------------------------------------------- |
| get\_data()     | Nhận dữ liệu lasted nếu realtime = False hoặc bắt đầu kết nối và nhận dữ liệu với realtime = True. |

```python
### pseudocode
event = client.Fetch_Trading_Data(
    realtime=False,
    tickers=tickers,
    fields=['open', 'high', 'low', 'close', 'volume', 'value', 'bu','sd'], 
    adjusted=True,
    by='1m', 
    from_date='2024-11-28 09:00'
)

data=event.get_data()
print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Mô tả                    | Kiểu dữ liệu |
| -------------- | ------------------------ | ------------ |
| ticker         | Tên mã.                  | str          |
| timestamp      | Thời gian giao dịch.     | str          |
| open           | Giá mở cửa.              | float        |
| low            | Giá thấp nhất.           | float        |
| high           | Giá cao nhất.            | float        |
| close          | Giá đóng cửa.            | float        |
| volume         | Khối lượng giao dịch.    | int          |
| value          | Giá trị giao dịch.       | int          |
| bu             | Khối lượng mua chủ động. | int          |
| sd             | Khối lượng bán chủ động. | int          |
| fb             | Giá trị mua khối ngoại.  | int          |
| fs             | Giá trị bán khối ngoại.  | int          |
| fn             | Giá trị mua/bán ròng.    | int          |

* Ví dụ

```python
import pandas as pd
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG', 'SSI', 'VN30F1M', 'UPCOMINDEX']
    
data = client.Fetch_Trading_Data(
    realtime = False,
    tickers = tickers,    
    fields = ['open', 'high', 'low', 'close', 'volume', 'value', 'bu', 'sd', 'fb', 'fs', 'fn'],
    adjusted=True,
    by = '1d', 
    from_date='2024-11-28',
).get_data()

print(data)
```


# 2.3. Hàm nối dữ liệu Realtime và lịch sử

Cơ chế hoạt động của hàm nối dữ liệu lịch sử và realtime:

* Tại thời điểm người dùng gọi lần đầu, thư viện sẽ lấy dữ liệu lịch sử phù hợp với timeframe người dùng gọi.
* Khi thông số realtime = True, thư viện sẽ kết nối dữ liệu qua websocket, và cập nhật data theo thời gian thực (realtime), các timeframe tiếp theo sẽ được tổng hợp từ dữ liệu realtime.

{% hint style="warning" %}
**Cảnh báo:** Do các timeframe được cập nhật tiếp theo thời gian thực, vì vậy việc duy trì kết nối ổn định sẽ đảm bảo dữ liệu được tổng hợp chính xác nhất. Đối với kết nối realtime, khuyến khích người dùng sử dụng đường truyền qua mạng có dây (LAN) và đường internet ổn định.

**Trường hợp cần đồng bộ với data từ server,** user có thể xây dựng cơ chế gọi lại hàm khi cần để lấy lại dữ liệu lịch sử tổng hợp trên server.&#x20;
{% endhint %}

Lưu ý: Do có một độ trễ nhỏ giữa server và phía thư viện nên khi thực thi code nối dữ liệu realtime, người dùng sẽ cần phải chờ một chút để dữ liệu được đồng bộ và chính xác.

Lưu ý: Khi truyền period ở chế độ realtime = True, period là số nến lịch sử. Tức là ví dụ ở lần gọi đầu tiên với period = 100 thì sẽ là 100 nến gần nhất, với nến thứ 100 là nến realtime vẫn đang được cập nhật. Và khi sang các nến khác thì dữ liệu trả về sẽ nhiều hơn 100.

```python
event = client.Fetch_Trading_Data(
    realtime = True, 
    tickers = tickers,
    fields = ['open','high','low','close','volume','value','bu','sd'], 
    by = by,
    callback = callback, 
    adjusted = True,
    period = 100,
    wait_for_full_timeFrame = False
)
```

**Tham số: (Lưu ý:** period chỉ tồn tại khi không truyền from\_date và ngược lại)

| Tên tham số                | Mô tả                                                                                                                             | Kiểu dữ liệu  | Mặc định | Bắt buộc       |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------- | -------------- |
| realtime                   | Có đăng ký vào dữ liệu update liên tục hay không hay chỉ gọi dữ liệu lịch sử đến thời điểm mới nhất (True là có, False là không). | bool          |          | Có.            |
| tickers                    | Danh sách mã được viết in hoa.                                                                                                    | str hoặc list |          | Có.            |
| fields                     | Các trường dữ liệu cần lấy. \['open','high','low','close','volume','bu','sd'] ứng với Open, High, Low, Close, Volume, BU, SD.     | list          |          | Có.            |
| adjusted                   | Giá điều chỉnh hay chưa điều chỉnh (True là đã điều chỉnh và ngược lại).                                                          | bool          | True     | Không.         |
| callback                   | Là hàm do người dùng tự định nghĩa để thao tác với dữ liệu.                                                                       | function      |          | Có.            |
| by                         | Đơn vị thời gian(1m, 5m, 15m, 30m, 1h, 2h, 4h, 1d).                                                                               | str           | 1M       | Không.         |
| period                     | Số nến lịch sử gần nhất cần lấy.                                                                                                  | int           |          | Không.         |
| from\_date                 | Mốc thời gian lấy dữ liệu xa nhất.                                                                                                | str           | datetime |                |
| to\_date                   | Mốc thời gian lấy dữ liệu gần nhất.                                                                                               | str           | datetime | datetime.now() |
| wait\_for\_full\_timeFrame | Chờ hết nến mới gọi callback hay khôngTrue là chờ hết cây nến.False là cập nhật liên tục.                                         | bool          | False.   | Không.         |
|                            |                                                                                                                                   |               |          |                |

**Hàm callback**

Là phương thức do người dùng tự định nghĩa để thao tác với dữ liệu, sẽ được truyền vào khi khởi tạo đối tượng nhận dữ liệu như là một đối số. Phương thức này sẽ có dạng như sau:

```python
### pseudocode

## callback_function
def name_of_callback(data: BarDataUpdate):
    ## do something

event = client.Fetch_Trading_Data(
    realtime=True,
    tickers=tickers,
    fields = ['open','high','low','close','volume','value','bu','sd'], 
    adjusted=True,
    callback=name_of_callback,
    by='1M', 
    from_date='2024-11-28 09:00'
)

event.get_data()
```

Dữ liệu cổ phiếu có các thuộc tính:

| Tên thuộc tính | Mô tả                   | Kiểu dữ liệu |
| -------------- | ----------------------- | ------------ |
| ticker         | Tên mã.                 | str          |
| timestamp      | Thời gian giao dịch.    | int          |
| open           | Giá mở cửa.             | float        |
| low            | Giá thấp nhất.          | float        |
| high           | Giá cao nhất.           | float        |
| close          | Giá đóng cửa.           | float        |
| volume         | Khối lượng giao dịch.   | int          |
| value          | Giá trị giao dịch.      | int          |
| bu             | Khối lượng mua.         | int          |
| sd             | Khối lượng bán.         | int          |
| fb             | Giá trị bán khối ngoại. | int          |
| fs             | Giá trị mua khối ngoại. | int          |
| fn             | Giá trị mua/bán ròng.   | int          |

Ví dụ

* Trường hợp 1: Sử dụng from\_date

Copy

```python
import time
import pandas as pd
from FiinQuantX import FiinSession, BarDataUpdate

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG', 'SSI', 'VNM', 'VIC', 'VRE']

def onUpdate(data: BarDataUpdate):
    print(data.to_dataFrame())
    print('-------------Callback-------------')
    
event = client.Fetch_Trading_Data(
    realtime = True,
    tickers = tickers,    
    fields = ['open','high','low','close','volume','value','bu','fn'],
    by = '1m', 
    callback = onUpdate, 
    from_date='2024-11-28 09:00',
    wait_for_full_timeFrame = False
)

event.get_data()

try:
    while not event._stop:
        time.sleep(1)
except KeyboardInterrupt:
    print("KeyboardInterrupt received, stopping...")
    event.stop()
```

* Trường hợp 2: Sử dụng period

Copy

```python
import time
import pandas as pd
from FiinQuantX import FiinSession, BarDataUpdate

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG', 'SSI', 'VN30', 'VN30F1M', 'VRE']

def onUpdate(data: BarDataUpdate):
    print(data.to_dataFrame())
    print('-------------Callback-------------')
    
event = client.Fetch_Trading_Data(
    realtime = True,
    tickers = tickers,    
    fields = ['open', 'high', 'low', 'close', 'volume', 'value', 'bu'],
    by = '1m', 
    period = 10,
    callback = onUpdate, 
    wait_for_full_timeFrame=False
)

event.get_data()
time.sleep(3600)
event.stop()
#Ví dụ chạy 1 giờ rồi ngưng.
```

| Tên phương thức | Mô tả                                                                                              |
| --------------- | -------------------------------------------------------------------------------------------------- |
| get\_data()     | Nhận dữ liệu lasted nếu realtime = False hoặc bắt đầu kết nối và nhận dữ liệu với realtime = True. |
| stop( )         | Dừng kết nối.                                                                                      |


# 2.4. Hàm dữ liệu sổ lệnh

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
event = client.BidAsk(tickers = tickers, callback = callback)
```

**Tham số**

<table><thead><tr><th>Tên tham số</th><th width="187">Mô tả</th><th>Kiểu dữ liệu</th><th>Bắt buộc</th></tr></thead><tbody><tr><td>tickers</td><td>Tên mã , bao gồm mã chứng khoán, mã chỉ số, mã phái sinh và mã chứng quyền. Các mã này được viết in hoa.</td><td><p>str hoặc list</p><p><br></p></td><td>Có</td></tr><tr><td>callback</td><td>Là hàm do người dùng tự định nghĩa để thao tác với dữ liệu.</td><td>function</td><td>Có</td></tr></tbody></table>

Class nhận dữ liệu là BidAsk, có 2 phương thức sau:

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F9d370Vba9Vx8mVLcNLw0%2Fimage.png?alt=media&amp;token=f871c40b-d6b5-4319-879f-02d2e24adfcd" alt=""><figcaption></figcaption></figure>

**Hàm callback**

Là phương thức do người dùng tự định nghĩa để thao tác với dữ liệu, sẽ được truyền vào khi khởi tạo đối tượng nhận dữ liệu như là một đối số. Phương thức này sẽ có dạng như sau:

```
//pseudocode
//callback_function
def name_of_callback(data: BidAskData):
    //do something

event = client.BidAsk(tickers = ['ticker_1','ticker_2',,,'ticker_n'], callback = name_of_callback)
event.start()
# tickers can include ticker, coveredwarrant, index and derivative.
event = client.BidAsk(tickers = ['ticker_1','ticker_2',,,'ticker_n'], callback = name_of_callback)
evente.start()
```

BidAskData có các phương thức và thuộc tính sau:

| Tên phương thức của object dữ liệu | Mô tả                                                                                                                  |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| to\_dataFrame( )                   | Trả về tất cả các thuộc tính của dữ liệu thay vì một thuộc tính riêng lẻ, được lưu trữ dưới dạng một Pandas DataFrame. |

**Dữ liệu BidAskData có các thuộc tính:**

<table><thead><tr><th width="163">Tên cột</th><th width="500">Mô tả</th><th>Kiểu dữ liệu</th></tr></thead><tbody><tr><td>ComGroupCode</td><td>Mã chỉ số.</td><td>str</td></tr><tr><td>StockType</td><td>Loại chứng khoán.</td><td>str</td></tr><tr><td>Ticker</td><td>Tên mã.</td><td>str</td></tr><tr><td>TradingDate</td><td>Thời gian.</td><td>str</td></tr><tr><td>Timestamp</td><td>Thời gian (làm tròn về giây).</td><td>str</td></tr><tr><td>Spread</td><td>Best1Ask - Best1Bid.</td><td>float</td></tr><tr><td>SpreadDelta</td><td>Spread tick hiện tại - Spread tick trước.</td><td>float</td></tr><tr><td>DepthImbalance</td><td>TotalBidVolume / (TotalBidVolume + TotalAskVolume).</td><td>float</td></tr><tr><td>TotalBuyTradeVolume</td><td>Tổng khối lượng giao dịch mua.</td><td>int</td></tr><tr><td>TotalSellTradeVolum</td><td>Tổng khối lượng giao dịch bán.</td><td>int</td></tr><tr><td>TotalBidVolume</td><td>Tổng khối lượng đặt mua.</td><td>int</td></tr><tr><td>TotalAskVolume</td><td>Tổng khối lượng đặt bán.</td><td>int</td></tr><tr><td>Best1Bid</td><td>Bước giá mua 1.</td><td>float</td></tr><tr><td>Best2Bid</td><td>Bước giá mua 2.</td><td>float</td></tr><tr><td>Best3Bid</td><td>Bước giá mua 3.</td><td>float</td></tr><tr><td>Best4Bid</td><td>Bước giá mua 4.</td><td>float</td></tr><tr><td>Best5Bid</td><td>Bước giá mua 5.</td><td>float</td></tr><tr><td>Best6Bid</td><td>Bước giá mua 6.</td><td>float</td></tr><tr><td>Best7Bid</td><td>Bước giá mua 7.</td><td>float</td></tr><tr><td>Best8Bid</td><td>Bước giá mua 8.</td><td>float</td></tr><tr><td>Best9Bid</td><td>Bước giá mua 9.</td><td>float</td></tr><tr><td>Best10Bid</td><td>Bước giá mua 10.</td><td>float</td></tr><tr><td>Best1Ask</td><td>Bước giá bán 1.</td><td>float</td></tr><tr><td>Best2Ask</td><td>Bước giá bán 2.</td><td>float</td></tr><tr><td>Best3Ask</td><td>Bước giá bán 3.</td><td>float</td></tr><tr><td>Best4Ask</td><td>Bước giá bán 4.</td><td>float</td></tr><tr><td>Best5Ask</td><td>Bước giá bán 5.</td><td>float</td></tr><tr><td>Best6Ask</td><td>Bước giá bán 6.</td><td>float</td></tr><tr><td>Best7Ask</td><td>Bước giá bán 7.</td><td>float</td></tr><tr><td>Best8Ask</td><td>Bước giá bán 8.</td><td>float</td></tr><tr><td>Best9Ask</td><td>Bước giá bán 9.</td><td>float</td></tr><tr><td>Best10Ask</td><td>Bước giá bán 10.</td><td>float</td></tr><tr><td>Best1BidVolume</td><td>Khối lượng đặt mua bước giá mua 1.</td><td>int</td></tr><tr><td>Best2BidVolume</td><td>Khối lượng đặt mua bước giá mua 2.</td><td>int</td></tr><tr><td>Best3BidVolume</td><td>Khối lượng đặt mua bước giá mua 3.</td><td>int</td></tr><tr><td>Best4BidVolume</td><td>Khối lượng đặt mua bước giá mua 4.</td><td>int</td></tr><tr><td>Best5BidVolume</td><td>Khối lượng đặt mua bước giá mua 5.</td><td>int</td></tr><tr><td>Best6BidVolume</td><td>Khối lượng đặt mua bước giá mua 6.</td><td>int</td></tr><tr><td>Best7BidVolume</td><td>Khối lượng đặt mua bước giá mua 7.</td><td>int</td></tr><tr><td>Best8BidVolume</td><td>Khối lượng đặt mua bước giá mua 8.</td><td>int</td></tr><tr><td>Best9BidVolume</td><td>Khối lượng đặt mua bước giá mua 9.</td><td>int</td></tr><tr><td>Best10BidVolume</td><td>Khối lượng đặt mua bước giá mua 10.</td><td>int</td></tr><tr><td>Best1AskVolume</td><td>Khối lượng đặt bán bước giá bán 1.</td><td>int</td></tr><tr><td>Best2AskVolume</td><td>Khối lượng đặt bán bước giá bán 2.</td><td>int</td></tr><tr><td>Best3AskVolume</td><td>Khối lượng đặt bán bước giá bán 3.</td><td>int</td></tr><tr><td>Best4AskVolume</td><td>Khối lượng đặt bán bước giá bán 4.</td><td>int</td></tr><tr><td>Best5AskVolume</td><td>Khối lượng đặt bán bước giá bán 5.</td><td>int</td></tr><tr><td>Best6AskVolume</td><td>Khối lượng đặt bán bước giá bán 6.</td><td>int</td></tr><tr><td>Best7AskVolume</td><td>Khối lượng đặt bán bước giá bán 7.</td><td>int</td></tr><tr><td>Best8AskVolume</td><td>Khối lượng đặt bán bước giá bán 8.</td><td>int</td></tr><tr><td>Best9AskVolume</td><td>Khối lượng đặt bán bước giá bán 9.</td><td>int</td></tr><tr><td>Best10AskVolume</td><td>Khối lượng đặt bán bước giá bán 10.</td><td>int</td></tr><tr><td>BidPriceDelta1</td><td>Chênh lệch bước giá mua 1 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta2</td><td>Chênh lệch bước giá mua 2 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta3</td><td>Chênh lệch bước giá mua 3 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta4</td><td>Chênh lệch bước giá mua 4 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta5</td><td>Chênh lệch bước giá mua 5 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta6</td><td>Chênh lệch bước giá mua 6 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta7</td><td>Chênh lệch bước giá mua 7 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta8</td><td>Chênh lệch bước giá mua 8 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta9</td><td>Chênh lệch bước giá mua 9 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidPriceDelta10</td><td>Chênh lệch bước giá  mua 10 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta1</td><td>Chênh lệch bước giá bán 1 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta2</td><td>Chênh lệch bước giá bán 2 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta3</td><td>Chênh lệch bước giá bán 3 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta4</td><td>Chênh lệch bước giá bán 4 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta5</td><td>Chênh lệch bước giá bán 5 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta6</td><td>Chênh lệch bước giá bán 6 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta7</td><td>Chênh lệch bước giá bán 7 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta8</td><td>Chênh lệch bước giá bán 8 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta9</td><td>Chênh lệch bước giá bán 9 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>AskPriceDelta10</td><td>Chênh lệch bước giá bán 10 tick hiện tại với tick trước.</td><td>float</td></tr><tr><td>BidVolumeDelta1</td><td>Chênh lệch khối lượng bước giá mua 1 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta2</td><td>Chênh lệch khối lượng bước giá mua 2 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta3</td><td>Chênh lệch khối lượng bước giá mua 3 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta4</td><td>Chênh lệch khối lượng bước giá mua 4 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta5</td><td>Chênh lệch khối lượng bước giá mua 5 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta6</td><td>Chênh lệch khối lượng bước giá mua 6 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta7</td><td>Chênh lệch khối lượng bước giá mua 7 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta8</td><td>Chênh lệch khối lượng bước giá mua 8 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta9</td><td>Chênh lệch khối lượng bước giá mua 9 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>BidVolumeDelta10</td><td>Chênh lệch khối lượng bước giá mua 10 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta1</td><td>Chênh lệch khối lượng bước giá bán 1 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta2</td><td>Chênh lệch khối lượng bước giá bán 2 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta3</td><td>Chênh lệch khối lượng bước giá bán 3 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta4</td><td>Chênh lệch khối lượng bước giá bán 4 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta5</td><td>Chênh lệch khối lượng bước giá bán 5 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta6</td><td>Chênh lệch khối lượng bước giá bán 6 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta7</td><td>Chênh lệch khối lượng bước giá bán 7 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta8</td><td>Chênh lệch khối lượng bước giá bán 8 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta9</td><td>Chênh lệch khối lượng bước giá bán 9 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>AskVolumeDelta10</td><td>Chênh lệch khối lượng bước giá bán 10 tick hiện tại với tick trước.</td><td>int</td></tr><tr><td>VWAPBid</td><td>Mức giá trung bình mà người mua sẵn sàng trả.</td><td>float</td></tr><tr><td>VWAPAsk</td><td>Mức giá trung bình mà người bán sẵn sàng chấp nhận.</td><td>float</td></tr><tr><td>VWAPBidSpread</td><td>Hiệu số giữa giá mua tốt nhất (Best1Bid) và VWAP Bid.</td><td>float</td></tr><tr><td>VWAPAskSpread</td><td>Hiệu số giữa VWAP Ask và giá bán tốt nhất (Best1Ask).</td><td>float</td></tr><tr><td>VWAPBidAskSpread</td><td>Chênh lệch giữa VWAP Ask và VWAP Bid.</td><td>float</td></tr><tr><td>OrderFlowImbalance</td><td>VWAPBidSpread/ (VWAPBidSpread + VWAPAskSpread).</td><td>float</td></tr></tbody></table>

Ví dụ về dữ liệu sổ lệnh (BidAskData):

<pre class="language-python"><code class="lang-python"><strong>from FiinQuantX import FiinSession, BidAskData
</strong><strong>
</strong>import pandas as pd
import time

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG','VNINDEX','VN30F1M']

def onTickerEvent(data: BidAskData):
    print('----------------')
    print(data.to_dataFrame())

Events = client.BidAsk(tickers=tickers, callback = onTickerEvent)
Events.start()

try:
    while not Events._stop: 
        time.sleep(1)
except KeyboardInterrupt:
    print("KeyboardInterrupt received, stopping...")
    Events.stop()
</code></pre>


# 2.5. Hàm theo dõi huỷ lệnh

{% hint style="info" %}
Hàm theo dõi hủy lệnh theo nguyên tắc theo dõi giá theo từng bước giá. Xác định khối lượng được thêm hay bớt.
{% endhint %}

<pre class="language-python"><code class="lang-python">from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

order_book = client.OrderBook()
<strong>
</strong>ticker_config = {
    "VJC": {"min_volume": 100_000},
    "VNM": {"min_volume": 100_000},
    "VPB": {"min_volume": 100_000},
    "VRE": {"min_volume": 100_000}
}

def process_data(data: dict):
    print(data)

# Theo dõi hủy lệnh bất thường
order_book.track_order_book_changes(ticker_config=ticker_config, action="add", accumulate_window=60, callback=process_data)

</code></pre>

| **Tham số**         | **Kiểu dữ liệu** | **Mô tả**                                                                                                 |
| ------------------- | ---------------- | --------------------------------------------------------------------------------------------------------- |
| ticker\_config      | dict             | Từ điển chứa từng mã chứng khoán và ngưỡng khối lượng thay đổi (min\_volume) cần cảnh báo                 |
| side                | str              | 'bid', 'ask' hoặc 'all' – chỉ định hướng theo dõi                                                         |
| action              | str              | 'cancel', 'add' hoặc 'all' – chỉ định loại thay đổi lệnh muốn theo dõi                                    |
| accumulate\_window  | int              | Đơn vị giây. Cho phép user định nghĩa tần suất tính lại để cộng tổng các giá trị hủy lệnh.                |
| min\_action\_volume | int              | Khối lượng cổ phiếu hủy/thêm tối thiểu để được tính là 1 lệnh hủy/thêm. Phục vụ thống kê số lệnh hủy/thêm |

1. Theo dõi bám theo giá cố định:
   * Mỗi mã được theo dõi ở mức giá cụ thể: bid2.price hoặc ask2.price (tùy side) ngay tại thời điểm khởi đầu.
   * Trong quá trình theo dõi, chỉ quan sát khối lượng tại đúng mức giá đó.
2. Ngưng theo dõi khi giá vượt giới hạn số bước giá hiển thị (3 bước/10 bước):
   * Nếu mức giá ban đầu bị đẩy ra khỏi vùng nhìn thấy:
     * Với HOSE: ngoài 3 bước giá tốt nhất (ví dụ: từ *bid1 đến bid3*)
     * Với HNX/UPCoM: ngoài 10 bước giá tốt nhất
   * Hệ thống sẽ ngưng theo dõi ticker đó, nhằm tránh bị nhiễu (noise) do sự thay đổi không thực chất.
3. Xử lý giá bid1 / ask1:
   * Giá bid1 / ask1 sẽ được trừ khối lượng đã khớp để tránh nhầm lẫn là hủy lệnh, khi thực tế là do khớp lệnh.
4. Tính OTR:

$$
OTR = \frac{Số lượng lệnh (đặt, sửa, hủy)}{Số lượng giao dịch thực hiện}
$$

Kết quả:

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FPGk3PjvyioAQ5tfdSE4W%2Fimage.png?alt=media&amp;token=bca9e108-9ccf-4320-a893-beb170f01580" alt=""><figcaption></figcaption></figure>

***

#### Ứng dụng thực tế:

* Phát hiện các dấu hiệu thao túng lệnh như đẩy giả lệnh mua/bán rồi hủy ngay sau đó.
* Phát hiện đột biến lượng lệnh đặt mới bất thường tại các vùng nhạy cảm.
* Phân tích hành vi nhà đầu tư/cá mập trong thời gian thực.


# 3. Phân tích cơ bản & Định giá


# 3.1. Báo cáo tài chính

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
fs_dict = client.FundamentalAnalysis().get_financial_statement(
    tickers=tickers,
    statement=statement,
    years=years,
    quarters=quarters,
    audited=True,
    type=type,
    fields=fields
)
```

**Tham số:**

| Tên tham số | Mô tả                                                                                                                                                                                                                                                                         | Kiểu dữ liệu  | Mặc định | Bắt buộc |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------- | -------- |
| tickers     | Danh sách mã được viết in hoa.                                                                                                                                                                                                                                                | str hoặc list |          | Có       |
| statement   | Loại báo cáo tài chính, là 1 trong 3 giá trị ‘balancesheet’, ‘incomestatement’, ‘cashflow’, hoặc ‘full’ là lấy hết. Nếu muốn lấy nhiều loại báo cáo tài chính thì liệt kê list các loại ra.                                                                                   | str           |          | Có       |
| years       | Năm của kỳ báo cáo, có thể chọn nhiều năm bằng cách liệt kê list các năm ra                                                                                                                                                                                                   | list\[int]    |          | Có       |
| quarters    | Quý của kỳ báo cáo, nếu không truyền mặc định lấy báo cáo tài chính của năm dựa trên tham số year, có thể chọn nhiều quý bằng cách liệt kê list các quý ra                                                                                                                    | list\[int]    | None     | Không    |
| audited     | Kiểm toán hay chưa (True là đã kiểm toán, False là chưa kiểm toán).                                                                                                                                                                                                           | bool          |          | Có       |
| type        | 1 trong 2 giá trị (‘consolidated’ hoặc ‘separate’). 'consolidated' là báo cáo tài chính hợp nhất, 'separate' là báo cáo tài chính công ty mẹ                                                                                                                                  | str           |          | Có       |
| fields      | Trường dữ liệu cần lấy (không truyền sẽ lấy hết). Biến fields có thể truyền theo dạng đường dẫn phân cấp cách nhau bằng dấu chấm ('Assets'.'CurrentAssets' – Lấy phần Tài sản ngắn hạn trong báo cáo tài chính) hoặc truyền thẳng sections là node cần lấy ('CurrentAssets'). | str           | None     | Không    |

Class nhận dữ liệu là FundamentalAnalysis và có phương thức nhận dữ liệu là get\_financial\_statement()

```python
### pseudocode
import json

fs_dict = client.FundamentalAnalysis().get_financial_statement(
    tickers=tickers,
    statement="balancesheet",
    years=[2024],
    quarters=[4],
    audited=True,
    type="consolidated"
)

print(json.dumps(fs_dict, indent=4))
```

* Ví dụ lấy dữ liệu full bảng cân đối kế toán của báo cáo tài chính hợp nhất đã kiểm toán quý 4 năm 2024 của mã HPG&#x20;

```python
import json

from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG']

fs_dict = client.FundamentalAnalysis().get_financial_statement(
    tickers=tickers,
    statement="balancesheet",
    years=[2024],
    quarters=[4],
    audited=True,
    type="consolidated"
)

print(json.dumps(fs_dict, indent=4))
```

Kết quả trả ra đầy đủ sẽ có cấu trúc ở phần [Mẫu dữ liệu BCTC hợp nhất](/huong-dan-python/cau-truc-du-lieu-mau/mau-du-lieu-bctc-hop-nhat)

* Ví dụ lấy dữ liệu các chỉ tiêu thuộc phần TỔNG TÀI SẢN thuộc bảng cân đối kế toán của báo cáo tài chính hợp nhất đã kiểm toán quý 4 năm 2024 của mã HPG

```python
import json

from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG']

fs_dict = client.FundamentalAnalysis().get_financial_statement(
    tickers=tickers,
    statement="balancesheet",
    years=[2024],
    quarters=[4],
    audited=True,
    type="consolidated",
    fields=["Assets"]
)

print(json.dumps(fs_dict, indent=4))
```

Kết quả trả ra:

```json
[
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 4,
        "reportType": "consolidated",
        "audited": true,
        "assets": {
            "totalAssets": 224489707553981,
            "currentAssets": {
                "shortTermInvestments": {
                    "totalShortTermInvestments": 18974716730905,
                    "tradingSecurities": 0,
                    "heldToMaturityInvestments": 18974716730905,
                    "provisionForTradingSecurities": 0
                },
                "shortTermReceivables": {
                    "tradeReceivables": 4352135419872,
                    "shortTermInternalReceivables": 0,
                    "receivablesUnderConstructionContracts": 0,
                    "advancesToSuppliers": 2118824427004,
                    "allowanceForDoubtfulReceivables": -159993736285,
                    "pendingAssetsShortage": 379714580,
                    "shortTermLoans": 87461616439,
                    "otherReceivables": 1248992845378,
                    "totalShortTermReceivables": 7647800286988
                },
                "inventories": {
                    "allowanceForImpairment": -101069892341,
                    "inventories": 46192292081813,
                    "totalInventories": 46091222189472
                },
                "totalCurrentAssets": 86674276272995,
                "cashAndCashEquivalents": {
                    "totalCashAndCashEquivalents": 6887646139852,
                    "cashEquivalents": 3968114193944,
                    "cash": 2919531945908
                },
                "otherCurrentAssets": {
                    "taxAndOrderReceivables": 10074967536,
                    "other": 0,
                    "governmentBondRepurchaseAgreement": 0,
                    "prepayments": 426149499088,
                    "totalOtherCurrentAssets": 7072890925778,
                    "deductibleValueAddedTax": 6636666459154
                }
            },
            "longTermAssets": {
                "otherLongTermAssets": {
                    "other": 0,
                    "deferredTaxAssets": 254671208385,
                    "prepayments": 4269141694868,
                    "longTermSparePartsAndEquipment": 429422385383,
                    "totalOtherLongTermAssets": 5016848415359,
                    "goodWill": 63613126723
                },
                "totalLongTermAssets": 137815431280986,
                "longTermAssetsInProgress": {
                    "constructionInProgress": 63655857440382,
                    "totalLongTermAssetsInProgress": 63750717325406,
                    "longTermWorkInProgress": 94859885024
                },
                "longTermInvestments": {
                    "provisionForLongTermInvestments": 0,
                    "heldToMaturityInvestments": 136500000000,
                    "totalLongTermInvestments": 136500000000,
                    "equityInvestmentsInOthers": 0,
                    "investmentsInSubsidiaries": 0,
                    "investmentsInJointVentures": 0
                },
                "fixedAssets": {
                    "intangibleFixedAssets": {
                        "cost": 367057604707,
                        "totalIntangibleFixedAssets": 184215978466,
                        "accumulatedAmortisation": -182841626241
                    },
                    "financeLeaseFixedAssets": {
                        "cost": 0,
                        "totalFinanceLeaseFixedAssets": 0,
                        "accumulatedDepreciation": 0
                    },
                    "totalFixedAssets": 67428366953514,
                    "tangibleFixedAssets": {
                        "cost": 108146566348954,
                        "totalTangibleFixedAssets": 67244150975048,
                        "accumulatedDepreciation": -40902415373906
                    }
                },
                "longTermReceivables": {
                    "longTermCustomerReceivables": 0,
                    "longTermAdvancesToSuppliers": 82805287792,
                    "capitalAtAffiliatedUnits": 0,
                    "otherLongTermReceivables": 840594835822,
                    "provisionForDoubtfulLongTermReceivables": 0,
                    "longTermIntercompanyReceivables": 0,
                    "longTermLoanReceivables": 0,
                    "totalLongTermReceivables": 923400123614
                },
                "investmentProperty": {
                    "cost": 860549015615,
                    "accumulatedDepreciation": -300950552522,
                    "totalInvestmentProperty": 559598463093
                }
            }
        },
        "companyType": "MANUFACTURING"
    }
]
```

* Ví dụ lấy dữ liệu các chỉ tiêu thuộc phần TÀI SẢN NGẮN HẠN nằm trong phần TỔNG TÀI SẢN thuộc bảng cân đối kế toán của báo cáo tài chính hợp nhất đã kiểm toán quý 4 năm 2024 của mã HPG

```python
import json

from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG']

fs_dict = client.FundamentalAnalysis().get_financial_statement(
    tickers=tickers,
    statement="balancesheet",
    years=[2024],
    quarters=[4],
    audited=True,
    type="consolidated",
    fields=["CurrentAssets"]
)

print(json.dumps(fs_dict, indent=4))
```

```json
[
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 4,
        "reportType": "consolidated",
        "audited": true,
        "currentAssets": {
            "shortTermInvestments": {
                "totalShortTermInvestments": 18974716730905,
                "tradingSecurities": 0,
                "heldToMaturityInvestments": 18974716730905,
                "provisionForTradingSecurities": 0
            },
            "shortTermReceivables": {
                "tradeReceivables": 4352135419872,
                "shortTermInternalReceivables": 0,
                "receivablesUnderConstructionContracts": 0,
                "advancesToSuppliers": 2118824427004,
                "allowanceForDoubtfulReceivables": -159993736285,
                "pendingAssetsShortage": 379714580,
                "shortTermLoans": 87461616439,
                "otherReceivables": 1248992845378,
                "totalShortTermReceivables": 7647800286988
            },
            "inventories": {
                "allowanceForImpairment": -101069892341,
                "inventories": 46192292081813,
                "totalInventories": 46091222189472
            },
            "totalCurrentAssets": 86674276272995,
            "cashAndCashEquivalents": {
                "totalCashAndCashEquivalents": 6887646139852,
                "cashEquivalents": 3968114193944,
                "cash": 2919531945908
            },
            "otherCurrentAssets": {
                "taxAndOrderReceivables": 10074967536,
                "other": 0,
                "governmentBondRepurchaseAgreement": 0,
                "prepayments": 426149499088,
                "totalOtherCurrentAssets": 7072890925778,
                "deductibleValueAddedTax": 6636666459154
            }
        },
        "companyType": "MANUFACTURING"
    }
]
```

* Ví dụ lấy dữ liệu chỉ tiêu PHẢI THU KHÁCH HÀNG thuộc bảng cân đối kế toán của báo cáo tài chính hợp nhất đã kiểm toán quý 4 năm 2024 của mã HPG

```python
import json

from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG']

fs_dict = client.FundamentalAnalysis().get_financial_statement(
    tickers=tickers,
    statement="balancesheet",
    years=[2024],
    quarters=[4],
    audited=True,
    type="consolidated",
    fields=["tradeReceivables"]
)

print(json.dumps(fs_dict, indent=4))
```

```json
[
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 4,
        "reportType": "consolidated",
        "audited": true,
        "tradeReceivables": 4352135419872,
        "companyType": "MANUFACTURING"
    }
]
```


# 3.2. Hàm chỉ số báo cáo tài chính

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
fi_dict = client.FundamentalAnalysis().get_ratios(
    tickers=tickers,
    years=years,
    quarters=quarters,
    type=type,
    fields=fields
)
```

**Tham số:**

| Tên tham số | Mô tả                                                                                                                                                                                                                             | Kiểu dữ liệu  | Mặc định | Bắt buộc |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------- | -------- |
| tickers     | Danh sách mã được viết in hoa.                                                                                                                                                                                                    | str hoặc list |          | Có       |
| years       | Năm của kỳ báo cáo, có thể chọn nhiều năm bằng cách liệt kê list các năm ra                                                                                                                                                       | list\[int]    |          | Có       |
| quarters    | Quý của kỳ báo cáo, nếu không truyền mặc định lấy báo cáo tài chính của năm dựa trên tham số year, có thể chọn nhiều quý bằng cách liệt kê list các quý ra                                                                        | list\[int]    | None     | Không    |
| type        | 1 trong 2 giá trị (‘consolidated’ hoặc ‘separate’). 'consolidated' là báo cáo tài chính hợp nhất, 'separate' là báo cáo tài chính công ty mẹ                                                                                      | str           |          | Có       |
| fields      | Trường dữ liệu cần lấy (không truyền sẽ lấy hết). Biến fields có thể truyền theo dạng đường dẫn phân cấp cách nhau bằng dấu chấm (ProfitabilityRatio'.'ROA' – Lấy chỉ số ROA) hoặc truyền thẳng sections là node cần lấy ('ROA'). | str           | None     | Không    |

Class nhận dữ liệu là FundamentalAnalysis và có phương thức nhận dữ liệu là get\_ratios()

```python
### pseudocode
import json

fi_dict = client.FundamentalAnalysis().get_ratios(
    tickers=tickers,
    years=[2024],
    quarters=[4],
    type="consolidated"
)

print(json.dumps(fi_dict, indent=4))
```

* Ví dụ lấy dữ liệu full chỉ số báo cáo tài chính hợp nhất của 4 quý trong năm 2024 của mã HPG

```python
import json

from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG']

fi_dict = client.FundamentalAnalysis().get_ratios(
    tickers=tickers,
    years=[2024],
    quarters=[1,2,3,4],
    type="consolidated"
)

print(json.dumps(fi_dict, indent=4))
```

Kết quả trả ra sẽ có cấu trúc giống với mục [Chỉ số cơ bản](/huong-dan-python/cau-truc-du-lieu-mau/chi-so-co-ban)hoặc [Mô tả trường dữ liệu chỉ số báo cáo tài chính gói nâng cao](/huong-dan-python/cau-truc-du-lieu-mau/mo-ta-truong-du-lieu-chi-so-bao-cao-tai-chinh-goi-nang-cao) tùy gói tài khoản

* Ví dụ lấy dữ liệu nhóm chỉ số báo cáo tài chính KHẢ NĂNG SINH LỢI dựa trên báo cáo tài chính hợp nhất của 4 quý năm 2024 của mã HPG

```python
import json

from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG']

fi_dict = client.FundamentalAnalysis().get_ratios(
    tickers=tickers,
    years=[2024],
    quarters=[1,2,3,4],
    type="consolidated",
    fields=["ProfitabilityRatio"]
)

print(json.dumps(fi_dict, indent=4))
```

Kết quả trả ra:

```json
[
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 1,
        "ratios": {
            "ProfitabilityRatio": {
                "GrossProfitMargin": 0.13464069,
                "EBITMargin": 0.10360069,
                "NetProfitMargin": 0.09299719,
                "ROA": 0.0503502,
                "ROE": 0.0917359,
                "ROIC": 0.06801845
            }
        }
    },
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 2,
        "ratios": {
            "ProfitabilityRatio": {
                "GrossProfitMargin": 0.13266118,
                "EBITMargin": 0.10394387,
                "NetProfitMargin": 0.08392193,
                "ROA": 0.05802448,
                "ROE": 0.10720898,
                "ROIC": 0.07589163
            }
        }
    },
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 3,
        "ratios": {
            "ProfitabilityRatio": {
                "GrossProfitMargin": 0.1393315,
                "EBITMargin": 0.10865351,
                "NetProfitMargin": 0.08898718,
                "ROA": 0.06034569,
                "ROE": 0.11376296,
                "ROIC": 0.07671273
            }
        }
    },
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 4,
        "ratios": {
            "ProfitabilityRatio": {
                "GrossProfitMargin": 0.12655218,
                "EBITMargin": 0.10487897,
                "NetProfitMargin": 0.08145881,
                "ROA": 0.05831798,
                "ROE": 0.11073185,
                "ROIC": 0.07400689
            }
        }
    }
]
```

* Ví dụ lấy dữ liệu chỉ số ROA thuộc nhóm chỉ số báo cáo tài chính KHẢ NĂNG SINH LỢI dựa trên báo cáo tài chính hợp của 4 quý năm 2024 của mã HPG

```python
import json

from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

tickers = ['HPG']

fi_dict = client.FundamentalAnalysis().get_ratios(
    tickers=tickers,
    years=[2024],
    quarters=[1,2,3,4],
    type="consolidated",
    fields=["ProfitabilityRatio.ROA"]
)

print(json.dumps(fi_dict, indent=4))
```

Kết quả trả ra:

```json
[
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 1,
        "ROA": 0.0503502
    },
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 2,
        "ROA": 0.05802448
    },
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 3,
        "ROA": 0.06034569
    },
    {
        "ticker": "HPG",
        "year": 2024,
        "quarter": 4,
        "ROA": 0.05831798
    }
]
```


# 3.3. Lấy dữ liệu định giá P/E, P/B theo mã chứng khoán

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.MarketDepth().get_stock_valuation(
    tickers=tickers,
    from_date=from_date,
    to_date=to_date
)
```

**Tham số:**

| Tên tham số | Mô tả                               | Kiểu dữ liệu  | Mặc định       | Bắt buộc |
| ----------- | ----------------------------------- | ------------- | -------------- | -------- |
| tickers     | Danh sách mã được viết in hoa.      | str hoặc list |                | Có       |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.  | str           |                | Có       |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất. | str           | datetime.now() | Không    |

Class nhận dữ liệu là MarketDepth và có phương thức nhận dữ liệu là get\_stock\_valuation()

```python
data = client.MarketDepth().get_stock_valuation(
    tickers=["HPG","MWG"],
    from_date="2025-08-28",
    to_date="2025-09-03"
)
print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Mô tả               | Kiểu dữ liệu |
| -------------- | ------------------- | ------------ |
| ticker         | Tên mã.             | str          |
| timestamp      | Thời gian giao dịch | str          |
| pe             | Chỉ số P/E          | float        |
| pb             | Chỉ số P/B          | float        |


# 3.4. Lấy dữ liệu định giá P/E, P/B theo nhóm Ngành

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.MarketDepth().get_sector_valuation(
    tickers=tickers,
    level=level,
    from_date=from_date,
    to_date=to_date
)
```

**Tham số:**

| Tên tham số | Mô tả                                                                                                                                       | Kiểu dữ liệu  | Mặc định       | Bắt buộc |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------------- | -------- |
| tickers     | Danh sách nhóm ngành (tham khảo tại [11.2. Danh sách nhóm ngành ICB](/ham-va-cong-thuc/11.-du-lieu-ho-tro/11.2.-danh-sach-nhom-nganh-icb)). | str hoặc list |                | Có       |
| level       | Cấp độ nhóm ngành                                                                                                                           | int           |                | Có       |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.                                                                                                          | str           |                | Có       |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất.                                                                                                         | str           | datetime.now() | Không    |

Class nhận dữ liệu là MarketDepth và có phương thức nhận dữ liệu là get\_stock\_valuation()

```python
data = client.MarketDepth().get_sector_valuation(
    tickers=["Banks","Insurance"],
    level=2,
    from_date="2025-08-28",
    to_date="2025-09-03"
)
print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Mô tả               | Kiểu dữ liệu |
| -------------- | ------------------- | ------------ |
| ticker         | Tên nhóm ngành.     | str          |
| timestamp      | Thời gian giao dịch | str          |
| pe             | Chỉ số P/E          | float        |
| pb             | Chỉ số P/B          | float        |


# 3.5. Lấy dữ liệu định giá P/E, P/B theo nhóm chỉ số

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.MarketDepth().get_index_valuation(
    tickers=tickers,
    from_date=from_date,
    to_date=to_date
)
```

**Tham số:**

| Tên tham số | Mô tả                               | Kiểu dữ liệu  | Mặc định       | Bắt buộc |
| ----------- | ----------------------------------- | ------------- | -------------- | -------- |
| tickers     | Danh sách nhóm chỉ số viết in hoa.  | str hoặc list |                | Có       |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.  | str           |                | Có       |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất. | str           | datetime.now() | Không    |

Class nhận dữ liệu là MarketDepth và có phương thức nhận dữ liệu là get\_stock\_valuation()

```python
data = client.MarketDepth().get_index_valuation(
    tickers=["VNINDEX","HNXIndex"],
    from_date="2025-08-28",
    to_date="2025-09-03"
)
print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Mô tả               | Kiểu dữ liệu |
| -------------- | ------------------- | ------------ |
| ticker         | Tên mã.             | str          |
| timestamp      | Thời gian giao dịch | str          |
| pe             | Chỉ số P/E          | float        |
| pb             | Chỉ số P/B          | float        |


# 4. Thống kê thị trường


# 4.1. Lấy dữ liệu về độ rộng thị trường (số mã sàn, số mã trần, số mã tăng/giảm/tham chiếu)

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Các ví dụ chi tiết được nêu ra ở cuối chương này.

```python
data = client.MarketBreadth().get(
    tickers=tickers
)
```

**Tham số:**

| Tên tham số | Mô tả                              | Kiểu dữ liệu  | Mặc định               | Bắt buộc |
| ----------- | ---------------------------------- | ------------- | ---------------------- | -------- |
| tickers     | Danh sách chỉ số được viết in hoa. | str hoặc list | Tất cả các nhóm chỉ số | Không    |

Toàn bộ nhóm chỉ số gồm có: **'VNINDEX', 'VN30', 'HNXIndex', 'HNX30', 'UpcomIndex', 'VNXALL', 'FLEADTRI', 'HNX30TRI', 'VN100', 'VN100TRI', 'VN30TRI', 'VNALL', 'VNALLTRI', 'VNCOND', 'VNCONS', 'VNDIAMOND', 'VNDTRI', 'VNENE', 'VNFIN', 'VNFINLEAD', 'VNFINSELECT', 'VNFSTRI', 'VNHEAL', 'VNIND', 'VNIT', 'VNMAT', 'VNMID', 'VNMIDCAPTRI', 'VNREAL', 'VNSI', 'VNSMALLTRI', 'VNSML', 'VNUTI', 'VNX50'**

Class nhận dữ liệu là MarketBreadth và có phương thức nhận dữ liệu là get()

```python
data = client.MarketBreadth().get()
print(data)
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính          | Mô tả                  | Kiểu dữ liệu |
| ----------------------- | ---------------------- | ------------ |
| comGroupCode            | Tên nhóm chỉ số        | str          |
| tradingDate             | Thời gian giao dịch    | str          |
| totalStockUpPrice       | Số cổ phiếu tăng       | int          |
| totalStockDownPrice     | Số cổ phiếu giảm       | int          |
| totalStockNoChangePrice | Số cổ phiếu tham chiếu | int          |
| totalStockUnderFloor    | Số mã sàn              | int          |
| totalStockOverCeiling   | Số mã trần             | int          |


# 4.2. Hàm độ rộng thị trường (chung)

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Đang phát triển ...


# 4.3 Hàm SeasonalityPrice

{% hint style="info" %}
Hàm này dùng để vẽ tương quan thay đổi giá của 1 hay nhiều mã cổ phiếu trong một khoảng thời gian
{% endhint %}

```python
import pandas as pd
import numpy as np
from plotly import graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

class SeasonalityPrice:
    def __init__(self, data, tickers):
        self.data = data
        self.data['timestamp'] = pd.to_datetime(self.data['timestamp'])
        self.tickers = []
        if isinstance(tickers, str):
            self.tickers = [tickers]
        elif isinstance(tickers, list):
            self.tickers = tickers
        else:
            self.tickers = [tickers]

    def monthly_seasonality(self):
        if len(self.tickers) > 1:
            raise ValueError("Only one ticker is supported for monthly seasonality")
        
        filtered_data = self.data.copy()
        filtered_data.set_index('timestamp', inplace=True)

        monthly_returns = filtered_data['close'].resample('M').last().pct_change() * 100
        monthly_seasonality = pd.DataFrame()
        monthly_seasonality['Month'] = monthly_returns.index.month
        monthly_seasonality['Year'] = monthly_returns.index.year
        monthly_seasonality['Returns'] = monthly_returns.values

        return monthly_seasonality
    
    
    def plot_seasonality(self):  
        if len(self.tickers) > 1:
            print("Tickers: ", self.tickers)

            raise ValueError("Only one ticker is supported for monthly seasonality")
        
        monthly_seasonality = self.monthly_seasonality()
        pivot_table = monthly_seasonality.pivot(index='Year', columns='Month', values='Returns').sort_index(ascending=True)
        monthly_averages = pivot_table.mean(axis=0).values.reshape(1, -1)  
        monthly_stdev = pivot_table.std(axis=0).values.reshape(1, -1)
        monthly_avg_plus_stdev = monthly_averages + monthly_stdev
        monthly_avg_minus_stdev = monthly_averages - monthly_stdev
        monthly_Sharpe_ratio = monthly_averages / monthly_stdev
        annotations = []
        for i, row in enumerate(pivot_table.values):
            for j, value in enumerate(row):
                annotations.append(
                    dict(
                        x=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][j],
                        y=pivot_table.index[i],
                        text=f'{value:.2f}' if not np.isnan(value) else '',
                        showarrow=False,
                        font=dict(color='black' if abs(value) < 10 else 'white')
                    )
                )
        fig = go.Figure()

        fig.add_trace(go.Heatmap(
            z=pivot_table.values,
            x=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            y=pivot_table.index,  
            colorscale=[
                [0, 'darkred'],      
                [0.49, '#ff6666'],   
                [0.5, 'white'],      
                [0.51, '#99ff99'],   
                [1, 'darkgreen']     
            ],
            colorbar_title="Returns (%)",
            showscale=False,
            zmin=-20,   
            zmax=20,
        ))

        # Add the averages heatmap
        fig.add_trace(go.Heatmap(
            z=monthly_averages,
            x= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            y=['Avgs: '],
            colorscale=[
                [0, 'darkred'],      
                [0.49, '#ff6666'],   
                [0.5, 'white'],      
                [0.51, '#99ff99'],   
                [1, 'darkgreen']     
            ],
            showscale=False,
            showlegend=False,
            text=monthly_averages,
            texttemplate='%{z:.2f}%',
            yaxis='y2',  
            xaxis='x2', 
        ))

        fig.add_trace(go.Heatmap(
            z=monthly_stdev,
            x= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            y=['Stdev: '],
            colorscale=[
                [0, 'darkred'],      
                [0.49, '#ff6666'],   
                [0.5, 'white'],      
                [0.51, '#99ff99'],   
                [1, 'darkgreen']     
            ],
            text=monthly_stdev,
            texttemplate='%{z:.2f}%',
            showscale=False,
            showlegend=False,
            yaxis= 'y3',
            xaxis= 'x3',
        ))
        fig.add_trace(go.Heatmap(
            z=monthly_avg_plus_stdev,
            x=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            y=['+ 1 stdev: '],
            colorscale=[
                [0, 'darkred'],      
                [0.49, '#ff6666'],   
                [0.5, 'white'],      
                [0.51, '#99ff99'],   
                [1, 'darkgreen']     
            ],
            showscale=False,
            showlegend=False,
            text=monthly_avg_plus_stdev,
            texttemplate='%{z:.2f}%',
            yaxis='y4',
            xaxis='x4',
        ))

        # Add the avg - 1stdev heatmap
        fig.add_trace(go.Heatmap(
            z=monthly_avg_minus_stdev,
            x=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            y=[' -1 stdev: '],
            colorscale=[
                [0, 'darkred'],      
                [0.49, '#ff6666'],   
                [0.5, 'white'],      
                [0.51, '#99ff99'],   
                [1, 'darkgreen']     
            ],
            showscale=False,
            showlegend=False,
            text=monthly_avg_minus_stdev,
            texttemplate='%{z:.2f}%',
            yaxis='y5',
            xaxis='x5',
        ))

        fig.update_layout(
            title=f'Monthly Percentage Price Change for {self.tickers} (2018-2024)',
            xaxis=dict(domain=[0, 1], showticklabels=False),
            yaxis=dict(domain=[0.5, 1.0], title='Year', autorange='reversed'),  
            xaxis2=dict(domain=[0, 1], anchor='y2', matches='x', showticklabels=False),
            yaxis2=dict(domain=[0.35,0.45], autorange='reversed'), 
            xaxis3=dict(domain=[0, 1], anchor='y3', matches='x',showticklabels=False),
            yaxis3=dict(domain=[0.24,0.34], autorange='reversed'), 
            yaxis4=dict(domain=[0.13,0.23], autorange='reversed'), 
            xaxis4=dict(domain=[0, 1], anchor='y4', matches='x', showticklabels=False),
            yaxis5=dict(domain=[0.02,0.12], autorange='reversed'), 
            xaxis5=dict(domain=[0, 1], anchor='y5', matches='x', title='Month'),
            annotations=annotations,
        )

        fig.show()

        fig_sharpe = go.Figure()

        sharpe_values = monthly_Sharpe_ratio.flatten()
        colors = ['#ff9999' if x < 0 else '#66b3ff' if x < 1 else '#99ff99' for x in sharpe_values]

        fig_sharpe.add_trace(go.Bar(
            x=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            y=sharpe_values,
            marker_color=colors,
            name='Sharpe Ratio'
        ))

        fig_sharpe.update_layout(
            title=f'Monthly Sharpe Ratio for {self.tickers} (2018-2024)',
            xaxis=dict(title='Month'),
            yaxis=dict(title='Sharpe Ratio'),
            plot_bgcolor='white',
            paper_bgcolor='white',
            showlegend=False,
            bargap=0.2
        )

        fig_sharpe.show()


    def plot_average_sharpe(self):
        monthly_sharpe_ratios = {}
        average_sharpe_ratios = {}

        for ticker in self.tickers:
            # Filter data for the current ticker
            ticker_data = self.data[self.data['ticker'] == ticker]
            ticker_data['timestamp'] = pd.to_datetime(ticker_data['timestamp'])
            mask = (ticker_data['timestamp'] >= '2018-01-01') & (ticker_data['timestamp'] <= '2024-11-30')
            filtered_data = ticker_data[mask].copy()

            filtered_data.set_index('timestamp', inplace=True)
            monthly_returns = filtered_data['close'].resample('ME').last().pct_change() * 100

            # Calculate monthly averages and standard deviations
            monthly_averages = monthly_returns.groupby(monthly_returns.index.month).mean()
            monthly_stdev = monthly_returns.groupby(monthly_returns.index.month).std()

            # Calculate Sharpe ratio
            sharpe_ratios = (monthly_averages / monthly_stdev).values
            monthly_sharpe_ratios[ticker] = sharpe_ratios
            average_sharpe_ratios[ticker] = np.nanmean(sharpe_ratios) 

        # Find the ticker with the highest average Sharpe ratio
        highest_avg_sharpe_ticker = max(average_sharpe_ratios, key=average_sharpe_ratios.get)
        highest_avg_sharpe_value = average_sharpe_ratios[highest_avg_sharpe_ticker]

        # Create subplots
        fig = make_subplots(rows=1, cols=2, shared_yaxes=False, horizontal_spacing=0.1,
                            subplot_titles=("Monthly Sharpe Ratios", "Average Sharpe Ratios"))

        months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        
        # Plot monthly Sharpe ratios
        for ticker, sharpe_values in monthly_sharpe_ratios.items():
            colors = ['#00FF00' if ticker == highest_avg_sharpe_ticker else '#ff9999' if value < 0 else '#66b3ff' if value < 1 else '#99ff99' for value in sharpe_values]
                    
            fig.add_trace(go.Bar(
                x=months,
                y=sharpe_values,
                marker_color=colors,
                name=f'Sharpe Ratio for {ticker}',
                width=0.15
            ), row=1, col=1)

        # Plot average Sharpe ratios
        avg_sharpe_values = list(average_sharpe_ratios.values())
        avg_colors = ['#00FF00' if ticker == highest_avg_sharpe_ticker else '#66b3ff' for ticker in tickers]
        
        fig.add_trace(go.Bar(
            x=tickers,
            y=avg_sharpe_values,
            marker_color=avg_colors,
            name='Average Sharpe Ratio',
            width=0.4
        ), row=1, col=2)

        # Add annotation for the highest average Sharpe ratio
        fig.add_annotation(
            x=highest_avg_sharpe_ticker, y=highest_avg_sharpe_value,
            text=f"Highest Avg Sharpe: {highest_avg_sharpe_ticker} ({highest_avg_sharpe_value:.2f})",
            showarrow=True,
            arrowhead=1,
            yshift=10,
            font=dict(size=12, color="black"),
            xref="x2", yref="y2"
        )

        fig.update_layout(
            title='Sharpe Ratios for Multiple Tickers (2018-2024)',
            xaxis=dict(title='Month'),
            yaxis=dict(title='Sharpe Ratio'),
            xaxis2=dict(title='Ticker'),
            yaxis2=dict(title='Average Sharpe Ratio', range=[0, max(avg_sharpe_values) * 1.2]),  # Scale y-axis
            plot_bgcolor='white',
            paper_bgcolor='white',
            showlegend=False,
            bargap=0.2
        )

        fig.show()


tickers = ['VCB', 'TPB', 'MBB','VIB','TCB', 'VPB', 'ACB', 'BID','CTG','EIB']

data = client.Fetch_Trading_Data(
    tickers=tickers,
    fields=['close'],
    adjusted=True,
    realtime=False,
    by='1d', 
    from_date='2018-01-01').get_data()
new_SeasonalityPrice = SeasonalityPrice(data, 'VCB')
new_SeasonalityPrice.plot_seasonality()

#Uncomment this to plot average sharpe ratio for multiple tickers
tickers = ['VCB', 'TPB', 'MBB','VIB','TCB', 'VPB', 'ACB', 'BID','CTG','EIB']
# new_SeasonalityPrice = SeasonalityPrice(data, tickers)
# new_SeasonalityPrice.plot_average_sharpe()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F0BiIK5VBr1xuK7Na5wSo%2FScreenshot%202025-02-18%20at%2010.21.14.png?alt=media&amp;token=8d8b6505-64a2-4b4b-a01b-3dd7c6f8032b" alt=""><figcaption><p>Bảng thay đổi giá theo tháng của VCB</p></figcaption></figure>

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FCrG4kj8dCZ6bX7tXHgv4%2FScreenshot%202025-02-18%20at%2010.22.25.png?alt=media&amp;token=9a0de6fb-3381-4ed8-9758-7f182dc6fea4" alt=""><figcaption><p>Sharpe Ratio theo tháng </p></figcaption></figure>


# 5. Định lượng & Phân tích nâng cao


# 5.1. Hiệu suất (Performance)


# 5.1.1. Annualize

Mục đích: chuyển đổi chuỗi thời gian các giá trị (ví dụ: lợi suất) thành giá trị thường niên (annualized), dựa trên tần suất quan sát trong chuỗi thời gian đó.

Cấu trúc hàm: annualize(x)

Trong đó:

* **x**: `Series` — chuỗi thời gian (TimeSeries - Series có index là dạng datetime) các giá trị như lợi suất, biến động (volatility), hoặc bất kỳ số liệu nào cần annualize.
* **Return**: `Series` — chuỗi thời gian đã được annualize.

Cơ chế:

* Tự động **ước lượng tần suất mẫu (sample frequency)** của chuỗi `x`, ví dụ: hàng ngày, hàng tuần, hàng tháng,...
* Sau đó tính **hệ số annualization** phù hợp và áp dụng công thức:

$$
Y\_t = X\_t . \sqrt{F}
$$

* Trong đó:
  * $$Y\_t$$ là giá trị thường niên tại thời điểm 𝑡
  * $$X\_t$$ là giá trị gốc tại thời điểm 𝑡
  * F là hệ số annualization (Annualization Factor)

Bảng hệ số annualization

| Kỳ quan sát          | Hệ số annualization (F) |
| -------------------- | ----------------------- |
| Daily (hàng ngày)    | 252                     |
| Weekly (hàng tuần)   | 52                      |
| Bi-Weekly            | 26                      |
| Monthly (hàng tháng) | 12                      |
| Quarterly (quý)      | 4                       |
| Annually (năm)       | 1                       |

Hàm này thường được dùng khi bạn có chuỗi thời gian là **returns hoặc volatility**, và bạn muốn:

* So sánh lợi suất thường niên giữa các cổ phiếu
* Tính độ biến động thường niên (annualized volatility)
* Chuẩn hóa dữ liệu để đưa vào mô hình tài chính

Nếu `returns(prices)` là chuỗi lợi suất hàng ngày, thì `annualized_returns` sẽ là lợi suất thường niên.

Lưu ý:

* Hàm `annualize()` sử dụng phương pháp **nhận diện tự động** tần suất dữ liệu (bằng cách đo khoảng cách giữa các `timestamp`) — bạn không cần cung cấp thông tin này.
* Trong thực tế, công thức annualization được dùng phổ biến nhất để **annualize volatility** (vì bản chất biến động cần được chuẩn hóa theo thời gian).

Ví dụ mẫu tính annualize return và annualize volatility của mã cổ phiếu HPG trong vòng 1 năm từ 24/06/2024 - 24/06/2025:

<pre class="language-python"><code class="lang-python">import pandas as pd

from FiinQuantX import FiinSession
from FiinQuantX.timeseries.econometrics import annualize
from datetime import datetime
from dateutil.relativedelta import relativedelta

<strong>username = "REPLACE_WITH_YOUR_USERNAME"
</strong>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()

# tính daily return
data["daily_return"] = data["close"] / data["close"].shift(1) - 1

# Đưa timestamp về dạng index để dùng trong hàm annyalize
data["timestamp"] = pd.to_datetime(data["timestamp"])
data.set_index("timestamp", inplace=True)

# Tính annualize returns
data["annualized_return"] = annualize(data["daily_return"])
print(data)
</code></pre>

Kết quả trả ra (code chạy tại ngày 25/06/2025)

```
 timestamp  ticker    close  daily_return  annualized_return
 2024-06-25 HPG       28700.0         NaN                NaN
 2024-06-26 HPG       28900.0    0.006969           0.110624
 2024-06-27 HPG       28850.0   -0.001730          -0.027465
 2024-06-28 HPG       28300.0   -0.019064          -0.302634
 2024-07-01 HPG       28350.0    0.001767           0.028047
 ...        ...           ...         ...                ...
 2025-06-18 HPG       27150.0    0.011173           0.177369
 2025-06-19 HPG       26900.0   -0.009208          -0.146174
 2025-06-20 HPG       27000.0    0.003717           0.059013
 2025-06-23 HPG       26850.0   -0.005556          -0.088192
 2025-06-24 HPG       27000.0    0.005587           0.088684
```

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

```python
import matplotlib.pyplot as plt

data = data.reset_index()
fig, ax1 = plt.subplots(figsize=(12, 6))

ax2 = ax1.twinx()
ax1.plot(data['timestamp'], data['close'], 'b-', label='Close Price')
ax2.plot(data['timestamp'], data['annualized_return'], 'g-', label='Annualized Return')

ax1.set_xlabel('Ngày')
ax1.set_ylabel('Giá đóng cửa (VND)', color='b')
ax2.set_ylabel('Lợi suất năm hoá (%)', color='g')
plt.title('Giá đóng cửa (VND) & Lợi suất năm hoá (%) của HPG của HPG')
plt.grid(True)
plt.show()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F63y0WKlErK6OGt2YbcPZ%2Fimage.png?alt=media&amp;token=0ea880d3-8b55-48b1-9eb2-a840852a0f4e" alt=""><figcaption></figcaption></figure>


# 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="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FQf5J25a78LLzb19kYg7e%2Fimage.png?alt=media&amp;token=cf745d56-8abd-421c-b17b-6d4af90a34b7" alt=""><figcaption></figcaption></figure>


# 5.2. Rủi ro (Risk)


# 5.2.1. Volatility

Mục đích: Dùng để **tính độ biến động (volatility) thực tế đã xảy ra** của một chuỗi giá tài sản, **theo kiểu rolling (trượt)** và được **chuẩn hóa theo năm (annualized)**.

Cấu trúc hàm: volatility(x, w=, returns\_type=Returns.SIMPLE)

Tham số:

<table><thead><tr><th width="85">Tham số</th><th width="104">Kiểu dữ liệu</th><th>Ý nghĩa</th></tr></thead><tbody><tr><td>x</td><td>Series</td><td>Chuỗi giá theo thời gian (Time series of prices).</td></tr><tr><td>w</td><td>Window / int / str</td><td>Kích thước cửa sổ trượt (rolling window):<br>– Ví dụ: <code>Window(22, 10)</code> là tính trên cửa sổ 22 phiên, bỏ qua 10 phiên đầu để "ramp-up".<br>– Có thể dùng kiểu chuỗi <code>"1m"</code> (1 tháng), <code>"10d"</code> (10 ngày)...<br>– Nếu không chỉ rõ, hàm tính trên toàn bộ chuỗi.</td></tr><tr><td>returns_type</td><td>Returns</td><td>Kiểu lợi suất cần dùng:<br>– <code>Returns.SIMPLE</code>: lợi suất đơn giản <span class="math">R_t = \frac{X_t}{X_{t - 1}} - 1</span><br>– <code>Returns.LOGARITHMIC</code>: lợi suất log tự nhiên <span class="math">R_t = \log({X_t}) - \log({X_{t - 1}})</span><br>– <code>Returns.ABSOLUTE</code>: thay đổi tuyệt đối <span class="math">R_t = X_t - X_{t - 1}</span></td></tr></tbody></table>

Ý nghĩa kết quả: Hàm trả về một chuỗi `Series` – biểu diễn **độ biến động hàng năm (annualized volatility)** của giá tài sản qua các cửa sổ thời gian đã chỉ định.

Công thức tính:

$$
Y\_t = \sqrt{\frac{1}{N - 1}\sum\_{i=t-w+1}^t(R\_i - \overline{R})^2} \* \sqrt{252} \* 100
$$

Trong đó:

* $$R\_i$$ là lợi suất tại thời điểm $$i$$ (dựa trên `returns_type`).
* $$\overline{R}$$ là trung bình lợi suất trong cửa sổ $$w$$.
* Nhân với $$\sqrt{252}$$ để annualize (giả định 252 ngày giao dịch trong năm).
* Nhân với 100 để ra dạng phần trăm (%).

Ví dụ mẫu tính rolling volatility 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 volatility
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["timestamp"] = pd.to_datetime(data["timestamp"])
data.set_index("timestamp", inplace=True)
data["vol_series_rampup"] = volatility(data["close"], w=Window(10, 5))
print(data)
```

Kết quả trả về:

<pre><code><strong>timestamp     ticker      close  vol_series_rampup
</strong>2024-06-26    HPG     24082.370                NaN
2024-06-27    HPG     24040.705                NaN
2024-06-28    HPG     23582.390                NaN
2024-07-01    HPG     23624.055                NaN
2024-07-02    HPG     23915.710                NaN
...           ...           ...                ...
2025-06-20    HPG     22499.100          19.390249
2025-06-23    HPG     22374.105          19.581153
2025-06-24    HPG     22499.100          19.349245
2025-06-25    HPG     22665.760          19.047278
2025-06-26    HPG     22800.000          14.427419
</code></pre>

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

```python
import matplotlib.pyplot as plt

# Biểu đồ với 2 trục y
fig, ax1 = plt.subplots(figsize=(12, 5))

# Trục y bên trái: giá
ax1.plot(data.index, data['close'], label='Giá đóng cửa', color='blue')
ax1.set_ylabel('Giá cổ phiếu', color='blue')
ax1.tick_params(axis='y', labelcolor='blue')

# Trục y bên phải: volatility
ax2 = ax1.twinx()
ax2.plot(data["vol_series_rampup"].index, data["vol_series_rampup"], label='Volatility (10 phiên)', color='red')
ax2.set_ylabel('Volatility (% annualized)', color='red')
ax2.tick_params(axis='y', labelcolor='red')

# Hoàn thiện biểu đồ
plt.title('Giá HPG và Volatility tính theo rolling 10 phiên')
fig.tight_layout()
plt.grid(True)
plt.show()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FjlAMAnHlERG2OAbpVbCM%2Fimage.png?alt=media&amp;token=321ed2bc-095a-482d-90fa-ae7163713e19" alt=""><figcaption></figcaption></figure>


# 5.2.2. Beta

Mục đích: Dùng để tính **rolling beta** giữa một chuỗi giá (hoặc lợi suất) và một chỉ số tham chiếu (benchmark), thường dùng để đo **mức độ nhạy cảm (rủi ro hệ thống)** của một cổ phiếu so với thị trường chung.

Cấu trúc hàm: beta(x, b, w=, prices=True)

Tham số:

<table><thead><tr><th width="82">Tham số</th><th width="174">Kiểu dữ liệu</th><th>Ý nghĩa</th></tr></thead><tbody><tr><td>x</td><td>Series</td><td>Chuỗi giá hoặc lợi suất của tài sản cần phân tích (ví dụ: cổ phiếu)</td></tr><tr><td>b</td><td>Series</td><td>Chuỗi giá hoặc lợi suất của benchmark (ví dụ: VNINDEX)</td></tr><tr><td>w</td><td>Window, int hoặc str</td><td>Kích thước cửa sổ rolling, ví dụ <code>Window(22, 10)</code> hoặc <code>'1m'</code>, <code>'1d'</code></td></tr><tr><td>prices</td><td>bool</td><td>Nếu <code>True</code>, <code>x</code> và <code>b</code> là chuỗi <strong>giá</strong>, sẽ được nội suy thành <strong>lợi suất</strong>; nếu <code>False</code>, bạn đã đưa vào lợi suất sẵn</td></tr></tbody></table>

Kiểu dữ liệu trả về: Trả về `Series` với chỉ số thời gian chứa giá trị beta được tính theo từng rolling window.

Công thức:

* Giả sử:
  * $$X\_t$$ và $$b\_t$$ là giá tài sản và benchmark tại thời điểm t
  * Tính lợi suất đơn giản:

$$
R\_t = \frac{X\_t}{X\_t - 1} - 1
$$

$$
S\_t = \frac{b\_t}{b\_t - 1} - 1
$$

* Thì:

$$
\beta\_{t} = \frac{Cov(R\_t, S\_t)}{Var(S\_t)}
$$

* Với mỗi cửa sổ `w`, beta được tính bằng **covariance giữa R và S chia cho variance của S**.

Hàm này thường được dùng để:

* Phân tích độ nhạy của cổ phiếu so với chỉ số thị trường (ví dụ: HPG so với VNINDEX)
* Phục vụ mô hình hóa rủi ro, CAPM, Alpha/Beta analysis

Lưu ý:

* Nếu bạn truyền vào chuỗi giá thì nhớ để `prices=True` để FiinQuant tự tính return.
* Nếu bạn đã tự tính return trước, hãy để `prices=False` để tránh tính toán sai.
* Đảm bảo `x` và `b` phải khớp thời gian (`index` phải trùng).

Ví dụ mẫu tính rolling beta trong vòng 22 ngày gần nhất từ 03/06/2025 - 25/06/2025 của HPG so với VNINDEX trên tập dữ liệu 1 năm từ 25/05/2024 - 25/06/2025:

```python
import pandas as pd
from FiinQuantX import FiinSession
from FiinQuantX.timeseries.econometrics import beta
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 và VNINDEX
data = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["HPG","VNINDEX"],
    fields=["close"],
    adjusted=True,
    by="1d",
    from_date=(datetime.now() - relativedelta(years=1)).strftime("%Y-%m-%d")
).get_data()

# Pivot theo ticker để tách riêng từng mã
data_pivot = data.pivot(index="timestamp", columns="ticker", values="close")

# Lấy Series
hpg_series = data_pivot["HPG"]
vnindex_series = data_pivot["VNINDEX"]

# Tính rolling beta 22 ngày
rolling_beta = beta(hpg_series, vnindex_series, w=Window(22), prices=True)

# Ghép 3 series vào thành 1 dataframe
df_hpg = hpg_series.rename("HPG").reset_index().rename(columns={"index": "timestamp"})
df_hsg = vnindex_series.rename("VNINDEX").reset_index().rename(columns={"index": "timestamp"})
df_corr = rolling_beta.rename("rolling_beta").reset_index().rename(columns={"index": "timestamp"})

df_merged = pd.merge(df_hpg, df_hsg, on="timestamp", how="outer")
df_merged = pd.merge(df_merged, df_corr, on="timestamp", how="outer")

df_merged = df_merged.sort_values("timestamp").reset_index(drop=True)
print(df_merged)
```

Kết quả trả ra (code chạy tại ngày 25/06/2025)

<pre><code><strong>     timestamp         HPG      VNINDEX  rolling_beta
</strong>0    2024-06-25 00:00  28700.0  1256.56           NaN
1    2024-06-26 00:00  28900.0  1261.24           NaN
2    2024-06-27 00:00  28850.0  1259.09           NaN
3    2024-06-28 00:00  28300.0  1245.32           NaN
4    2024-07-01 00:00  28350.0  1254.56           NaN
..                ...      ...      ...           ...
244  2025-06-18 00:00  27150.0  1346.83      0.189324
245  2025-06-19 00:00  26900.0  1352.04      0.220260
246  2025-06-20 00:00  27000.0  1349.35      0.211598
247  2025-06-23 00:00  26850.0  1358.18      0.136014
248  2025-06-24 00:00  27000.0  1366.77      0.142753
</code></pre>

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

```python
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Chuẩn hóa giá trị
df_merged['timestamp'] = pd.to_datetime(df_merged['timestamp'])
df_merged['HPG_norm'] = (df_merged['HPG'] - df_merged['HPG'].min()) / (df_merged['HPG'].max() - df_merged['HPG'].min())
df_merged['VNINDEX_norm'] = (df_merged['VNINDEX'] - df_merged['VNINDEX'].min()) / (df_merged['VNINDEX'].max() - df_merged['VNINDEX'].min())

fig, ax1 = plt.subplots(figsize=(14, 6))

# Trục y bên trái: giá HPG và VNINDEX
ax1.plot(df_merged['timestamp'], df_merged['HPG_norm'], label='HPG (normalized)', color='blue')
ax1.plot(df_merged['timestamp'], df_merged['VNINDEX_norm'], label='VNINDEX (normalized)', color='green', linestyle='--')
ax1.set_ylabel('Normalized Price', color='black')
ax1.legend(loc='upper left')
ax1.grid(True)

# Format x-axis
ax1.xaxis.set_major_locator(mdates.AutoDateLocator())
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate(rotation=45)  # Rotate labels for readability

# Trục y bên phải: rolling beta
ax2 = ax1.twinx()
ax2.plot(df_merged['timestamp'], df_merged['rolling_beta'], label='Rolling Beta', color='red', alpha=0.6)
ax2.set_ylabel('Rolling Beta', color='red')
ax2.legend(loc='upper right')

plt.title('Diễn biến HPG, VNINDEX và Rolling Beta theo thời gian')
plt.tight_layout()
plt.show()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FQGtyK8UYzob9douOV9Yv%2Fimage.png?alt=media&amp;token=7edc8c75-da68-454a-9fd5-cb327655bea7" alt=""><figcaption></figcaption></figure>


# 5.3. Tương quan & So sánh


# 5.3.1. Correlation

Mục đích: Dùng để **tính hệ số tương quan trượt (rolling correlation)** giữa hai chuỗi thời gian giá hoặc lợi suất trong tài chính.

Cấu trúc hàm: correlation(x, y, w=, type\_=SeriesType.PRICES)

Tham số:

<table><thead><tr><th width="82">Tham số</th><th width="174">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 thứ nhất (giá hoặc lợi suất)</td></tr><tr><td>y</td><td>Series</td><td>Chuỗi thời gian thứ hai (giá hoặc lợi suất)</td></tr><tr><td>w</td><td>Window, int hoặc str</td><td>Kích thước cửa sổ trượt (rolling window)<br>Ví dụ: <code>Window(22, 10)</code> là dùng cửa sổ 22 phiên và bỏ qua 10 phiên đầu để "ramp-up".<br>Nếu dùng <code>str</code>, có thể là <code>'1m'</code> (1 tháng), <code>'1d'</code> (1 ngày)...</td></tr><tr><td>type_</td><td>SeriesType.PRICES (mặc định) hoặc SeriesType.RETURNS</td><td>Xác định đầu vào là giá hay lợi suất</td></tr></tbody></table>

Ý nghĩa toán học: Hàm tính hệ số tương quan Pearson giữa hai chuỗi lợi suất (hoặc giá được chuyển thành lợi suất) trong cửa sổ trượt `w`.

Công thức:

$$
\rho\_t = \frac{\sum\_{i=t-w+1}^t (R\_i - \overline{R})(S\_i - \overline{S})}{(N-1).\sigma\_{R}.\sigma\_{S}}
$$

Trong đó:

* $$R\_i = \frac{X\_i}{X\_i - 1}$$: lợi suất từ chuỗi `x` nếu input là giá.
* $$S\_i = \frac{Y\_i}{Y\_i - 1}$$: lợi suất từ chuỗi `y` nếu input là giá.
* Nếu input đã là lợi suất thì dùng trực tiếp $$R\_i = X\_i$$, $$S\_i = Y\_i$$.
* $$\overline{R}$$, $$\overline{S}$$: trung bình mẫu trong mỗi cửa sổ.
* $$\sigma\_{R}$$, $$\sigma\_{S}$$: độ lệch chuẩn mẫu trong mỗi cửa sổ.

Giá trị trả về:

* Một `Series` chứa hệ số tương quan qua từng thời điểm ttt, tương ứng với mỗi cửa sổ trượt.
* Có thể dùng để đánh giá mối quan hệ đồng biến/nghịch biến theo thời gian.

Ví dụ mẫu tính rolling correlation trong vòng 22 ngày gần nhất từ 03/06/2025 - 25/06/2025 của HPG và HSG trên tập dữ liệu 1 năm từ 25/05/2024 - 25/06/2025:

<pre class="language-python"><code class="lang-python">import pandas as pd
from FiinQuantX import FiinSession
from FiinQuantX.timeseries.econometrics import correlation
from FiinQuantX.timeseries.helper import Window
<strong>from datetime import datetime
</strong>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 và HSG
data = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["HPG","HSG"],
    fields=["close"],
    adjusted=True,
    by="1d",
    from_date=(datetime.now() - relativedelta(years=1)).strftime("%Y-%m-%d")
).get_data()

# Pivot theo ticker để tách riêng từng mã
data["timestamp"] = pd.to_datetime(data["timestamp"])
pivot_data = data.pivot(index="timestamp", columns="ticker", values="close")

# Lấy Series
series_HPG = pivot_data["HPG"]
series_HSG = pivot_data["HSG"]

# Tính rolling correlation 22 ngày
corr = correlation(series_HPG, series_HSG, w=22)

# Ghép 3 series vào thành 1 dataframe
df_hpg = series_HPG.rename("HPG").reset_index().rename(columns={"index": "timestamp"})
df_hsg = series_HSG.rename("HSG").reset_index().rename(columns={"index": "timestamp"})
df_corr = corr.rename("correlation").reset_index().rename(columns={"index": "timestamp"})

df_merged = pd.merge(df_hpg, df_hsg, on="timestamp", how="outer")
df_merged = pd.merge(df_merged, df_corr, on="timestamp", how="outer")

df_merged = df_merged.sort_values("timestamp").reset_index(drop=True)
print(df_merged)
</code></pre>

Kết quả trả ra (code chạy tại ngày 25/06/2025)

```
   timestamp   HPG      HSG       correlation
0  2025-01-24  26550.0  16954.42          NaN
1  2025-02-03  26400.0  17100.16          NaN
2  2025-02-04  26850.0  17391.64          NaN
3  2025-02-05  26800.0  17391.64          NaN
4  2025-02-06  26800.0  17245.90          NaN
..        ...      ...       ...          ...
95 2025-06-19  26900.0  16750.00     0.674208
96 2025-06-20  27000.0  16600.00     0.661541
97 2025-06-23  26850.0  16350.00     0.667212
98 2025-06-24  27000.0  16750.00     0.655733
99 2025-06-25  27200.0  16750.00     0.668507
```

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

```python
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Chuẩn hóa giá HPG và HSG (min-max normalization)
df_merged['timestamp'] = pd.to_datetime(df_merged['timestamp'])
df_merged['HPG_norm'] = (df_merged['HPG'] - df_merged['HPG'].min()) / (df_merged['HPG'].max() - df_merged['HPG'].min())
df_merged['HSG_norm'] = (df_merged['HSG'] - df_merged['HSG'].min()) / (df_merged['HSG'].max() - df_merged['HSG'].min())

fig, ax1 = plt.subplots(figsize=(14, 6))

# Plot HPG và HSG đã chuẩn hóa
ax1.plot(df_merged['timestamp'], df_merged['HPG_norm'], label='HPG (normalized)', color='blue')
ax1.plot(df_merged['timestamp'], df_merged['HSG_norm'], label='HSG (normalized)', color='green')
ax1.set_ylabel('Normalized Price', color='black')
ax1.legend(loc='upper left')
ax1.grid(True)

# Format thời gian
ax1.xaxis.set_major_locator(mdates.AutoDateLocator())
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate(rotation=45)

# Trục y phải: correlation
ax2 = ax1.twinx()
ax2.plot(df_merged['timestamp'], df_merged['correlation'], label='Rolling Correlation (HPG-HSG)', color='red', linestyle='--')
ax2.set_ylabel('Correlation', color='red')
ax2.legend(loc='upper right')

plt.title('Giá HPG & HSG (chuẩn hóa) và hệ số tương quan theo thời gian')
plt.tight_layout()
plt.show()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FkVsLsxmiGNGWzCu8Avbf%2Fimage.png?alt=media&amp;token=5f707298-6fc0-4bbf-b619-ed66adec490d" alt=""><figcaption></figcaption></figure>


# 5.3.2. FindDateCorrelation

{% hint style="info" %}
Sử dụng function này để tìm mối tương quan giữa dữ liệu ngày hôm nay và dữ liệu trong quá khứ cho một mã nhất định.
{% endhint %}

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2Funn2psxlKOHZxiPPZFt3%2Fimage.png?alt=media&amp;token=b9569c87-dbf4-4b47-b9c1-be14e159a7fc" alt=""><figcaption><p>Ví dụ tìm kiếm tương quan cho VN30F1M trong 1 năm dữ liệu so với ngày hiện tại</p></figcaption></figure>

<pre class="language-python"><code class="lang-python">
 def intraday_Correlation(self, Ticker: Union[str, list[str]], Timeframe: str, 
                            t1: str = None, t2: str = None, method: str = "pearson correlation",
<strong>                            year: int = 1) -> None:
</strong></code></pre>

#### Tham số&#x20;

| Tham số     | Kiểu dữ liệu            | Mặc định | Giá trị mặc định        | Mô tả                                                                     |
| ----------- | ----------------------- | -------- | ----------------------- | ------------------------------------------------------------------------- |
| `Ticker`    | `Union[str, list[str]]` | Bắt buộc | Không có                | Mã chứng khoán hoặc danh sách mã chứng khoán cần phân tích.               |
| `Timeframe` | `str`                   | Bắt buộc | 1M                      | Khung thời gian của dữ liệu giao dịch nội ngày (ví dụ: "1m", "5m", "1h"). |
| `t1`        | `str`                   | Tùy chọn | 9am hoặc 13pm           | Thời gian bắt đầu (nếu cần).                                              |
| `t2`        | `str`                   | Tùy chọn | `None`                  | Thời gian kết thúc (nếu cần).                                             |
| `method`    | `str`                   | Tùy chọn | `"pearson correlation"` | Phương pháp đo khoảng cách (1: Euclidean, 2: DTW, 3: Pearson, 4: Cosine). |
| `year`      | `int`                   | Tùy chọn | `1`                     | Số năm dữ liệu quá khứ cần so sánh.                                       |

Copy đoạn code để chạy ví dụ trên&#x20;

```python

import pandas as pd
import datetime

from FiinQuantX import FiinSession
from datetime import datetime

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'
 
client = FiinSession(
    username=username,
    password=password
).login()

def user_input():
    default_timeframe = '1m'
    default_t1 = "09:00:00" if datetime.now().hour < 12 else "13:00:00"
    default_t2 = datetime.now().replace(microsecond=0).time().strftime("%H:%M:%S")
    default_method = "pearson correlation"
    default_year = 1
    print("")
    print("Chào mừng đến hệ thống dự báo biểu đồ CHỨNG KHOÁN theo THỜI GIAN THỰC của FIINQUANT")
    print("")
    print("Giải thích cách tìm top 5 ngày tương quan:")
    print("")
    print("- Tìm kiếm tất cả các pattern nến của tất cả các ngày trong vòng x năm kể từ thời điểm hiện tại")
    print("- Tìm 5 ngày có độ tương quan với ngày hiện tại nhất dựa trên các phương pháp tùy người chọn: Euclidean Distance, Pearson Correlation (mặc định), cosine")
    print("")
    print("Hệ thống sẽ sử dụng các tham số mặc định sau:")
    print(f"- Khung thời gian: {default_timeframe}")
    print(f"- Thời điểm bắt đầu: {default_t1}")
    print(f"- Thời điểm kết thúc (là thời điểm hiện tại): {default_t2}")
    print(f"- Phương pháp tính tương quan: {default_method}")
    print(f"- Số năm dữ liệu muốn quét kể từ thời điểm hiện tại: {default_year} năm")

    use_default = input("Bạn có muốn sử dụng các tham số mặc định không? (y/n): ").lower() == "y"

    if not use_default:
        timeframe = input("Nhập khung thời gian (ví dụ: 1m, 15m, 30m, 1h mặc định: 1m): ") or default_timeframe
        t1 = input("Nhập thời điểm bắt đầu (ví dụ: 09:00, 10:00, 11:00): ")
        t2 = input("Nhập thời điểm kết thúc (ví dụ: 13:00, 14:00, 15:00): ")
        
        print("Vui lòng lựa chọn phương pháp tính tương quan:")
        print("1. Pearson Correlation (mặc định)")
        print("2. Euclidean Distance")
        print("3. Cosine")
        print("4. Dynamic Time Wrapping")
        method = int(input("Lựa chọn của bạn (1/2/3): ")) or 1
        
        year = int(input("Nhập số năm dữ liệu muốn quét kể từ thời điểm hiện tại: ")) or 1
    else:
        timeframe = default_timeframe
        t1 = default_t1
        t2 = default_t2
        method = default_method
        year = default_year
    
    Ticker = input("Vui lòng nhập mã bạn muốn so tìm đường tương quan (ví dụ: VN30, VN30F1M, ACB): ")
    print("Đang tính toán, vui lòng đợi")
    client.FindDateCorrelation().intraday_Correlation(Ticker=Ticker, Timeframe=timeframe, t1=t1, t2=t2, method=method, year=year)


# Chạy chương trình
if __name__ == "__main__":
    user_input()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FahvAI3OuDTBWE0vTyUe4%2Fimage.png?alt=media&amp;token=c594f5a7-3a06-41a3-87b4-a196f13134d2" alt=""><figcaption></figcaption></figure>


# 5.3.3. SimilarChart

{% hint style="info" %}
Cho phép người dùng tìm kiếm nhanh trong số lượng lớn mã cổ phiếu 5 mã có xu hướng giá gần nhất với mã cổ phiếu đang quan tâm.&#x20;
{% endhint %}

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FMr2ApuZmHjmBMgtf5Hp0%2Fimage.png?alt=media&amp;token=cf1a8c66-ba5e-4ecc-9a2f-41bda5fa764d" alt=""><figcaption><p>5 mã cổ phiếu có xu hướng gần nhất với mã ACB hiện tại </p></figcaption></figure>

```python
client.SimilarChart().plot(Ticker=Ticker, t1=t1, t2=t2)
```

**Tham số**

| Tên tham số | Mô tả                          | Kiểu dữ liệu | Giá trị mặc định |
| ----------- | ------------------------------ | ------------ | ---------------- |
| Ticker      | Mã cổ phiếu áp dụng            | Ticker       | Không có         |
| t1          | Thời điểm bắt đầu của cụm nến  | str          |                  |
| t2          | Thời điểm kết thúc của cụm nến | str          |                  |

```python
import pandas as pd
from FiinQuantX import FiinSession
import datetime
from datetime import datetime
from dateutil.relativedelta import relativedelta

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

def user_input():
    default_t1 = (datetime.now() - relativedelta(months=1)).strftime("%Y-%m-%d")
    default_t2 = datetime.now().strftime("%Y-%m-%d")
    print("")
    print("Chào mừng đến hệ thống dự báo biểu đồ CHỨNG KHOÁN theo THỜI GIAN THỰC của FIINQUANT")
    print("")
    print("Giải thích cách tìm chart có đường giá tương đồng với đường giá thời điểm hiện tại:")
    print("")
    print("- Tìm kiếm tất cả các pattern nến của tất cả các ngày trong vòng x năm kể từ thời điểm hiện tại")
    print("- Tìm ngày có đường giá giống với ngày hiện tại nhất")
    print("")
    print("Hệ thống sẽ sử dụng các tham số mặc định sau:")
    print(f'- Thời điểm bắt đầu: {default_t1}')
    print(f'- Thời điểm kết thúc (là thời điểm hiện tại): {default_t2}')

    use_default = input("Bạn có muốn sử dụng các tham số mặc định không? (y/n): ").lower() == "y"

    if not use_default:
        t1 = input("Nhập ngày bắt đầu (ví dụ: 2024-05-10): ")
        t2 = input("Nhập thời điểm kết thúc (ví dụ: 2024-05-10): ")
    else:
        t1 = default_t1
        t2 = default_t2
    
    Ticker = input("Vui lòng nhập mã bạn muốn so tìm đường tương quan (ví dụ: VN30, VN30F1M, ACB): ")
    Ticker = Ticker.upper()    
    print("Đang tính toán, vui lòng đợi")
    client.SimilarChart().plot(Ticker=Ticker, t1=t1, t2=t2)

if __name__ == "__main__":
    user_input()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FDCrIVCg5ZefT3v4Q6Fvi%2Fimage.png?alt=media&amp;token=40f18a1e-52c8-498b-b4b6-1af100a0160a" alt=""><figcaption></figcaption></figure>


# 5.3.4. Hàm thời vụ hành vi (Seasonality theo sự kiện, tháng, ngày, kỳ nghỉ lễ…)

Nhóm hàm liên quan đến thống kê hiệu suất của cổ phiếu trước và sau thời điểm nghỉ lễ hoặc 1 ngày bất kỳ trong tháng qua các năm

Cấu trúc hàm: seasonality(ticker, event=None, month=None, day=None, before=5, after=5, period=10)

Các tham số

<table><thead><tr><th width="99">Tham số</th><th width="113">Kiểu dữ liệu</th><th>Mô tả</th></tr></thead><tbody><tr><td>ticker</td><td>str</td><td>Mã cổ phiếu muốn theo dõi thời vụ hành vi.</td></tr><tr><td>event</td><td>str</td><td>Sự kiện muốn theo dõi hiệu suất của cổ phiếu trước và sau sự kiện, có thể bỏ trổng. Nếu bỏ trống buộc phải điều tham số month và day. Nếu không bỏ trống chỉ được phép điền 1 trong 5 sự kiện sau: new_year_eve, tet_holiday, commemoration_day, liberation_day, independence_day. </td></tr><tr><td>month</td><td>int</td><td>Có thể bỏ trống, nếu bỏ trống buộc phải điền tham số event. Nếu không bỏ trống điền tháng muốn chọn (từ 1 đến 12)</td></tr><tr><td>day</td><td>int</td><td>Có thể bỏ trống, nếu bỏ trống buộc phải điền tham số event. Nếu không bỏ trống điền ngày muốn chọn</td></tr><tr><td>before</td><td>int</td><td>Số phiến trước ngày nghỉ lễ hoặc ngày bất kỳ muốn thống kê. Mặc định là 5</td></tr><tr><td>after</td><td>int</td><td>Số phiến sau ngày nghỉ lễ hoặc ngày bất kỳ muốn thống kê. Mặc định là 5</td></tr><tr><td>period</td><td>int</td><td>Số năm muốn thống kê. Mặc định là 10</td></tr></tbody></table>

Giá trị trả về: Danh sách phân tích gồm các thông tin sau

* Số năm tăng, số năm giảm
* Tỷ suất sinh lời trung bình
* Trung vị
* Biến động (Std Dev)
* Hiệu suất sinh lời cao nhất
* Hiệu suất sinh lời thấp nhất

Ví dụ về việc phân tích hiệu suất 5 ngày trước và sau Ngày Quốc Khánh của VNINDEX trong vòng 10 năm

```python
from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

client.seasonality(ticker="VNINDEX", event="independence_day")
```

Kết quả trả ra cho ví dụ chạy tại ngày 25/06/2025

```
📈 Seasonality Analysis của mã VNINDEX trước và sau Ngày Quốc Khánh (5 ngày trước / 5 ngày sau):
- Tăng: 4 năm | Giảm: 6 năm
- Tỷ suất sinh lời trung bình: -0.30%
- Trung vị: -0.39%
- Biến động (Std Dev): 1.61%
- Lớn nhất: +1.75%
- Nhỏ nhất: -2.41%
```


# 6. Chiến lược & công cụ


# 6.1. Rebalance

Bằng cách nhập giá trị có thể mua và mã index, thuật toán sẽ tính ra số lượng cổ phiếu cần mua để có tỷ lệ giống với tỷ lệ cổ phiếu trong rổ chỉ số index nhất. Ứng dụng trong giao dịch arbitrage, passive investment.

{% hint style="info" %}
Phương pháp luận hàm **Rebalance:**

Hàm **Rebalance** sử dụng dữ liệu công bố của Sở giao dịch chứng khoán về Tỷ lệ FreeFloat, Giới hạn tỷ trọng kết hợp với giá đóng cửa (close price) realtime của hệ thống FiinGroup.

**Tái cơ cấu** được thực hiện theo nguyên tắc tỷ lệ về **Khối lượng không thay đổi trong một danh mục**, do vậy để có thể bám theo (tracking) một chỉ số, người quản trị danh mục chỉ cần xây dựng bộ **danh mục có tỷ lệ về số lượng giữa các cổ phiếu giống với tỷ lệ về chỉ số** cần theo dõi, sẽ đảm bảo đạt được độ lệch (Tracking Error) thấp nhất.

Kết quả trả ra là **"Share to Buy"** dựa trên input đầu vào là **Budget (VND)** và **Ticker (Chỉ số)** cần **Rebalance**.
{% endhint %}

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F8kk3fjlVjiUizlhgEhMa%2Fimage.png?alt=media&amp;token=b7a46d2c-978f-4329-9d24-c80fc00120e0" alt="" width="375"><figcaption><p>Danh sách vã số lượng cần mua của mỗi mã cổ phiếu</p></figcaption></figure>

Danh sách các Index dùng cho hàm:

* VN30
* VN100
* VNX50
* VNMidcap
* VNFINSELECT
* VNDIAMOND
* VNFINLEAD

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'                     
                     
client = FiinSession(username=username, password=password).login()
df = client.Rebalance().get(Budget = 10000000000, Ticker = 'VN30')
print(df)
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FOeeWeNGURzMOBM70mOc6%2Fimage.png?alt=media&amp;token=f54df53c-9060-4174-bcbd-69c9a7af42eb" alt=""><figcaption></figcaption></figure>


# 6.2. Biểu đồ sức mạnh giá (RRG)

Bằng cách nhập danh sách mã cổ phiếu cần tính, tên index benchmark, hàm sẽ tính ra **hiệu suất tương đối của cổ phiếu** và **chỉ số chuẩn hoặc một nhóm cổ phiếu cụ thể** để từ đó xác định hiệu suất tương đối của một cổ phiếu để phân loại thuộc 1 trong 4 trạng thái sau:

* Tăng trưởng (Góc phần tư tăng trưởng): Cổ phiếu trong góc phần tư này đang thể hiện sức mạnh tương đối mạnh mẽ và động lực tích cực so với mức chuẩn. Là những cổ phiếu đang hoạt động tốt hơn thị trường hoặc lĩnh vực rộng lớn hơn và được coi là cổ phiếu dẫn đầu về hiệu suất giá. Những cổ phiếu này được coi là ứng cử viên chốt lời hoặc tiếp tục nắm giữ lợi nhuận tiềm năng.
* Tích lũy (Góc phần tư tích lũy): Cổ phiếu trong góc phần tư này đang có dấu hiệu cải thiện về sức mạnh tương đối, cho thấy rằng chúng đang lấy đà và rất dễ chuyển sang trạng thái tăng trưởng. Những cổ phiếu này được coi là ứng cử viên Mua tiềm năng.
* Suy yếu (Góc phần tư suy yếu): Các cổ phiếu trong góc phần tư này đang có sự suy giảm sức mạnh tương đối so với mức chuẩn. Mặc dù chúng có thể vẫn đang trong xu hướng tăng nhưng đà tăng của chúng đang chậm lại hoặc mất dần sức mạnh so với giai đoạn trước. Những cổ phiếu này được phân loại là có tiềm năng giảm giá hoặc bán khống. Việc chốt lời các cổ phiếu dạng này là cần thiết.
* Giảm giá (Góc phần tư giảm giá): Cổ phiếu trong góc phần tư này đang hoạt động kém hơn so với điểm chuẩn. Chúng đang có sức mạnh tương đối yếu và có thể đang gặp khó khăn tăng trưởng so với các cổ phiếu khác. Nhà đầu tư nên tránh mua những cổ phiếu thuộc nhóm này vì chúng đang yếu hơn thị trường chung.

**Tham số (Lưu ý:** period chỉ tồn tại khi không truyền from\_date và ngược lại). Và phải lựa chọn 1 trong 2 cách truyền này)**:**

| Tên tham số | Mô tả                                               | Kiểu dữ liệu  | Mặc định       | Bắt buộc |
| ----------- | --------------------------------------------------- | ------------- | -------------- | -------- |
| tickers     | Danh sách mã được viết in hoa.                      | str hoặc list |                | Có       |
| benchmark   | Index benchmark để tính RS và RM                    | str           |                | Có       |
| by          | Đơn vị thời gian(1m, 5m, 15m, 30m, 1h, 2h, 4h, 1d). | str           | 1d             | Không    |
| from\_date  | Mốc thời gian lấy dữ liệu xa nhất.                  | str           |                | Có       |
| to\_date    | Mốc thời gian lấy dữ liệu gần nhất.                 | str           | datetime.now() | Không    |
| period      | Số nến lịch sử gần nhất cần lấy.                    | int           |                | Không    |

Class nhận dữ liệu là Fetch\_Trading\_Data và 3 phương thức sau:

| Tên phương thức | Mô tả                                                                                                      |
| --------------- | ---------------------------------------------------------------------------------------------------------- |
| get()           | Nhận dữ liệu dạng dataframe trả ra có các thuộc tính mô tả như bên dưới.                                   |
| filter()        | Nhận dữ liệu dạng dataframe sau đó lọc ra các dòng dữ liệu thỏa mãn các điều kiện do người dùng truyền vào |
| plot()          | Được dùng sau khi nhận dữ liệu từ phương thức get, thực hiện trực quan hóa biểu đồ                         |

Ví dụ lấy dữ liệu RRG - dùng phương thức get()

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'                     
                     
client = FiinSession(username=username, password=password).login()
rrg = client.RRG(
    tickers=["ACB"],
    benchmark="VNINDEX",
    by='1d',
    from_date="2024-10-10"
)
df_rrg = rrg.get()
print(df_rrg)
```

Dữ liệu trả ra có các thuộc tính:

| Tên thuộc tính | Mô tả                                                                              | Kiểu dữ liệu |
| -------------- | ---------------------------------------------------------------------------------- | ------------ |
| ticker         | Tên mã.                                                                            | str          |
| timestamp      | Thời gian giao dịch.                                                               | str          |
| close          | Giá đóng cửa.                                                                      | float        |
| rs             | Sức mạnh (S-Strength)                                                              | float        |
| rm             | Xu hướng (S-treand)                                                                | float        |
| phase          | Giai đoạn thuộc 1 trong 4 trạng thái sau: Weakening, Lagging, Improving và Leading | str          |

Ví dụ bộ lọc RRG dựa trên tiêu chí do người dùng truyền vào - dùng phương thức filter()

**Các tham số của phương thức filter:**

| Tên tham số   | Mô tả                                                                                 | Kiểu dữ liệu  | Mặc định | Bắt buộc |
| ------------- | ------------------------------------------------------------------------------------- | ------------- | -------- | -------- |
| tickers       | Danh sách mã muốn lọc được viết in hoa.                                               | str hoặc list |          | Không    |
| date          | Ngày muốn xem RRG                                                                     | str           |          | Không    |
| phase         | Lọc ra những ngày có trạng thái là Weakening hoặc Lagging hoặc Improving hoặc Leading | str           |          | Không    |
| rs\_min       | Số sức mạnh rs tối thiểu                                                              | float         |          | Không    |
| rs\_max       | Số sức mạnh rs tối đa                                                                 | float         |          | Không    |
| rm\_min       | Số xu hướng rm tối thiểu                                                              | float         |          | Không    |
| rm\_max       | Số xu hướng rm tối đa                                                                 | float         |          | Không    |
| changed\_only | Sàng lọc những ngày đổi trạng thái                                                    | bool          | False    | Không    |

* Ví dụ lọc các giai đoạn Leading có chỉ số sức mạnh RS và chỉ số xu hướng RM tối thiểu là 101 của mã ACB

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'                     
                     
client = FiinSession(username=username, password=password).login()
rrg = client.RRG(
    tickers=["ACB"],
    benchmark="VNINDEX",
    by='1d',
    from_date="2024-10-10"
)
leading_high_rs = rrg.filter(
    rs_min=101,
    rm_min=101,
)
print(leading_high_rs)
```

Dữ liệu trả ra có các thuộc tính tương tự phương thức get()

Trực quan hóa biểu đồ RRG - dùng phương thức plot() (Lưu ý: Buộc phải lấy dữ liệu dùng phương thức get() rồi sau đó mới dùng được phương thức plot())

* Ví dụ

```python
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'                     
                     
client = FiinSession(username=username, password=password).login()
rrg = client.RRG(
    tickers=["ACB"],
    benchmark="VNINDEX",
    by='1d',
    from_date="2024-10-10"
)
df_rrg = rrg.get()
rrg.plot(trail_length=30)
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FOmYqQ4mEvopUXDp9vJp9%2FFigure_1.png?alt=media&amp;token=b09a4348-47b8-4938-9dec-cce041158b86" alt=""><figcaption></figcaption></figure>


# 7. Hàm Đặt Lệnh

Được thiết kế để kết nối với các công ty chứng khoán, hiện tại là DNSE, giúp người dùng có thể đặt lệnh thông qua API và thực hiện các tác vụ liên quan đến định lượng mà không cần mở bảng giá.


# 7.1. Đăng nhập

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Đăng nhập connector thông qua fiinquant.

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()
```

**Tham số:**

| Tham số    | Kiểu dữ liệu | Bắt buộc | Mô tả                                                                                                                                                  |
| ---------- | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| broker     | str          | Có       | Tên của sàn giao dịch mà bạn muốn kết nối. Ví dụ: 'DNSE' (hiện FiinQuant mới hỗ trợ kết nối đến sàn giao dịch DNSE).                                   |
| username   | str          | Có       | Tên đăng nhập tài khoản giao dịch của bạn tại sàn.                                                                                                     |
| password   | str          | Có       | Mật khẩu đăng nhập tài khoản giao dịch của bạn tại sàn.                                                                                                |
| smart\_otp | bool         | Không    | Cờ (flag) chỉ định có sử dụng **Smart OTP** để xác thực đăng nhập. True thì lấy OTP qua app, False thì lấy qua mail. Chỉ cần nhập 1 lần trong 8 tiếng. |

Sau khi thực hiện bước này, ở máy user sẽ xuất hiện file dạng **“trading\_token…...json”**. File này dùng để chương trình đọc và thực thi các bước đặt lệnh mà không cần lấy lại otp. Trading\_token có hiệu lực trong khoảng 8 tiếng, nếu hết hạn hệ thống sẽ yêu cầu nhập lại otp. User nên tuyệt đối giữ bí mật file này.

Các hàm từ đây sẽ trả ra object, user có thể truy cập đến thuộc tính của các object đó, hoặc gọi hàm **summary()** để lấy ra ra một số thông tin cơ bản.


# 7.2. Thông tin tài khoản

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

### 7.2.1. **Thông tin tài khoản chính**

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

account_info = client_order.get_account_info()
print(account_info.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': '0001006289',
    'investor_id': '0001006289',
    'name': 'DANG THANH THUY',
    'error': None,
    'status_code': 200
}
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Kiểu dữ liệu  | Mô tả                                                              |
| -------------- | ------------- | ------------------------------------------------------------------ |
| id             | str           | Mã định danh duy nhất của tài khoản (có thể là id hoặc accountId). |
| investor\_id   | str           | Mã định danh của nhà đầu tư.                                       |
| name           | str           | Họ và tên đầy đủ của nhà đầu tư hoặc chủ tài khoản.                |
| error          | str hoặc None | Thông báo lỗi (nếu có) từ phản hồi của API. Không có lỗi thì None. |
| status\_code   | int           | Mã code, nếu thành công là 200                                     |

### 7.2.2. **Thông tin tiểu khoản**

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

sub_accounts = client_order.get_sub_accounts()
for account in sub_accounts.accounts:
    print(account.summary())
print(sub_accounts.default.id) # phương thức lấy tiểu khoản mặc định
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': '0001177757',
    'investor_id': '0001006289',
    'custody_code': '064C500006',
    'derivative_account': False,
    'derivative_status': None,
    'status_code': 200
}
{
    'id': '0001009212',
    'investor_id': '0001006289',
    'custody_code': '064C500006',
    'derivative_account': True,
    'derivative_status': 'ACTIVE',
    'status_code': 200
}
```

Mô tả object:

* BaseSubAccount (Abstract class, không phải Base là cơ sở)

| Tên thuộc tính      | Kiểu dữ liệu  | Mô tả                                                  |
| ------------------- | ------------- | ------------------------------------------------------ |
| id                  | str           | Mã định danh của tiểu khoản.                           |
| custody\_code       | str           | Mã lưu ký chứng khoán của nhà đầu tư.                  |
| investor\_id        | str           | Mã định danh của nhà đầu tư.                           |
| derivative\_account | bool          | Cho biết đây có phải là tài khoản phái sinh hay không. |
| derivative\_status  | str hoặc None | Trạng thái của tài khoản phái sinh (nếu có).           |

* BaseSubAccountInfo(chứa các BaseSubAccount)

| Tên thuộc tính | Kiểu dữ liệu          | Mô tả                                        |
| -------------- | --------------------- | -------------------------------------------- |
| default        | BaseSubAccount        | Tài khoản mặc định được chọn của nhà đầu tư. |
| accounts       | List\[BaseSubAccount] | Danh sách tiểu khoản                         |
| error          | str hoặc None         | Thông tin lỗi (nếu có).                      |
| status\_code   | int                   | Mã code, nếu thành công là 200               |


# 7.3. Thông tin gói vay (nguồn tiền)

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

### 7.3.1. Gói vay thường

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

loan_packages = client_order.get_loan_packages(account_id='0001009212')
for i in loan_packages:
    print(i.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': 7905,
    'type': 'M',
    'initial_rate': 0.5,
    'maintenance_rate': 0.4,
    'interest_rate': 0.12,
    'preferential_interest_rate': 0.12,
    'allow_extend': True,
    'allow_early_payment': True,
    'buy_fee': 0.0007,
    'sell_fee': 0.0007,
    'tickers': ['ACB', 'BCC', 'BID', 'BVS',
                'CTG', 'FPT', 'GEX', 'HPG',
                'LPB', 'MBB', 'MBS', 'POW',
                'PVC', 'SHS', 'SSI', 'TCB',
                'VCB', 'VND', 'VPB'],
    'error': None,
    'status_code': 200,
    'num_tickers': 19
}
```

Dữ liệu có các thuộc tính:

* BaseLoanPackage

| Tên thuộc tính               | Kiểu dữ liệu  | Mô tả                                                                                         |
| ---------------------------- | ------------- | --------------------------------------------------------------------------------------------- |
| id                           | str           | Mã định danh gói vay.                                                                         |
| type                         | str           | Loại gói vay: M = Margin (ký quỹ), N = Normal (thông thường).                                 |
| initial\_rate                | float         | Tỷ lệ vay ban đầu (Initial Rate).                                                             |
| maintenance\_rate            | float         | Tỷ lệ duy trì (Maintenance Rate). Nếu giá trị tài sản thấp hơn mức này, có thể bị gọi ký quỹ. |
| interest\_rate               | float         | Lãi suất vay ký quỹ (%/năm).                                                                  |
| preferential\_interest\_rate | float         | Lãi suất ưu đãi trong giai đoạn khuyến mãi.                                                   |
| allow\_extend                | bool          | Cho phép gia hạn thời hạn vay hay không.                                                      |
| allow\_early\_payment        | bool          | Cho phép tất toán trước hạn hay không.                                                        |
| buy\_fee                     | float         | Phí giao dịch mua do công ty chứng khoán quy định.                                            |
| sell\_fee                    | float         | Phí giao dịch bán do công ty chứng khoán quy định.                                            |
| tickers                      | list hoặc str | Danh sách mã chứng khoán được phép áp dụng gói vay.                                           |
| error                        | str hoặc None | Thông tin lỗi (nếu có) khi lấy dữ liệu gói vay.                                               |
| status\_code                 | int           | Mã code, nếu thành công là 200                                                                |

### 7.3.1. Gói vay phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

der_loans = client_order.get_derivative_loan_packages(account_id='0001009212')
for i in der_loans:
    print(i.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': 2278,
    'initial_rate': 0.1848,
    'maintenance_rate': 0.1771,
    'liquid_rate': 0.1731,
    'trading_fee': 500.0,
    'trading_fee_daily_close': 500.0,
    'symbol_types': ['V100F1M', 'V100F2M', 'VN30F1M',
                     'VN30F1Q', 'VN30F2M', 'VN30F2Q'],
    'error': None,
    'num_symbol_types': 6,
    'status_code': 200
}
```

Dữ liệu có các thuộc tính:

* Class BaseDerivativeLoanPackage

| Tên thuộc tính             | Kiểu dữ liệu  | Mô tả                                                                          |
| -------------------------- | ------------- | ------------------------------------------------------------------------------ |
| id                         | str           | Mã định danh của gói vay phái sinh.                                            |
| error                      | str hoặc None | Thông tin lỗi (nếu có) khi lấy dữ liệu.                                        |
| initial\_rate              | float         | Tỷ lệ ký quỹ ban đầu (Initial Margin Rate).                                    |
| maintenance\_rate          | float         | Tỷ lệ duy trì ký quỹ (Maintenance Margin Rate).                                |
| liquid\_rate               | float         | Tỷ lệ xử lý (Liquidation Margin Rate) — mức yêu cầu đóng vị thế bắt buộc.      |
| trading\_fee               | float         | Phí giao dịch cố định cho mỗi lần giao dịch.                                   |
| trading\_fee\_daily\_close | float         | Phí giao dịch cố định hàng ngày.                                               |
| ticker\_types              | list hoặc str | Danh sách loại hợp đồng phái sinh được áp dụng (ví dụ: VN30F1M, VN30F2M, ...). |
| status\_code               | int           | Mã code, nếu thành công là 200                                                 |


# 7.4. Khởi tạo OrderBook để thao tác với các hàm đặt lệnh

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Kể từ phần này về sau sẽ thao tác thông qua class orderbook, việc khởi tạo orderbook cần thông tin về account\_id(tiểu khoản) và loan\_id (nguồn tiền). Từ đó ta sử dụng orderbook để thao tác với các hàm đặt lệnh, mỗi orderbook sẽ đi kèm với thông tin về mã tiểu khoản và nguồn tiền (loan\_id).

### 7.4.1. Orderbook cho thị trường cơ sở

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(account_id='0001009212', loan_id='13720')
```

### 7.4.2. Orderbook cho thị trường phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)
```

Ở phái sinh có hàm cài chiến lược chốt lời cắt lỗ theo tiểu khoản (nếu muốn).

Cách dùng:

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

orderbook_der.set_derivative_tp_sl_strategy(
    take_profit_rate = 0.05,
    stop_loss_rate = -0.05
)
```

**Tham số:**

| Tham số                    | Kiểu dữ liệu | Bắt buộc                 | Mô tả                                                                                                                                                              |
| -------------------------- | ------------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| take\_profit\_rate         | float        | Không *(mặc định = 0.0)* | <p>Tỷ lệ chốt lời (%), tính trên giá vốn. Khi giá tăng đến mức tương ứng, hệ thống sẽ đặt lệnh chốt lời.</p><p>Yêu cầu nếu có: x>0</p>                             |
| stop\_loss\_rate           | float        | Không *(mặc định = 0.0)* | <p>Tỷ lệ cắt lỗ (%), tính trên giá vốn. Khi giá giảm đến mức tương ứng, hệ thống sẽ đặt lệnh cắt lỗ.</p><p>Yêu cầu nếu có: -1<=x<0</p>                             |
| take\_profit\_delta\_price | float        | Không *(mặc định = 0.0)* | <p>Khoảng chênh lệch giá tuyệt đối (theo điểm giá) dùng để xác định mức chốt lời. Ưu tiên sử dụng nếu không dùng take\_profit\_rate.</p><p>Yêu cầu nếu có: x>0</p> |
| stop\_loss\_delta\_price   | float        | Không *(mặc định = 0.0)* | <p>Khoảng chênh lệch giá tuyệt đối (theo điểm giá) dùng để xác định mức cắt lỗ. Ưu tiên sử dụng nếu không dùng stop\_loss\_rate.</p><p>Yêu cầu nếu có: x>0</p>     |

* LƯU Ý: orderbook hay orderbook\_der chỉ là tên biến giả định (user đặt là gì cũng được, chỉ có tên hàm là cố định). Giả định ta đã khởi tạo 2 orderbook này rồi, từ các bước sau sẽ sử dụng 2 biến này cho các ví dụ (orderbook và orderbook\_der).


# 7.5. Thông tin tiền

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)
cash_info = orderbook.get_balance()
print(cash_info.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'investor_id': '0001006289',
    'account_id': '0001009212',
    'custody_code': '064C500006',
    'available_cash': 4884924031998,
    'stock_value': 208451161632,
    'withdrawable_cash': 4884923201540,
    'net_asset_value': 5093681360108,
    'margin_debt': 470067960.0,
    'margin_rate': 10000000.0,
    'error': None,'status_code': 200
}
```

Dữ liệu có các thuộc tính:

* Class BaseAccountBalance

| Tên thuộc tính    | Kiểu dữ liệu  | Mô tả                                          |
| ----------------- | ------------- | ---------------------------------------------- |
| account\_id       | str           | Mã định danh tiểu khoản.                       |
| investor\_id      | str           | Mã định danh nhà đầu tư sở hữu tài khoản.      |
| custody\_code     | str           | Mã lưu ký (custody code) của nhà đầu tư.       |
| available\_cash   | float         | Số tiền mặt có thể sử dụng ngay.               |
| stock\_value      | float         | Giá trị danh mục cổ phiếu hiện tại.            |
| net\_asset\_value | float         | Tổng giá trị tài sản ròng của tài khoản (NAV). |
| margin\_debt      | float         | Số tiền vay ký quỹ hiện tại.                   |
| margin\_rate      | float         | Tỷ lệ ký quỹ hiện tại (%).                     |
| error             | str hoặc None | Thông tin lỗi (nếu có).                        |
| status\_code      | int           | Mã code, nếu thành công là 200                 |


# 7.6. Sức mua/bán

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

### 7.6.1. Cơ bản

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)
trade_cap = orderbook.get_trading_power(ticker='SSI', price=41200)
print(trade_cap.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

<pre class="language-json"><code class="lang-json"><strong>{
</strong>    'investor_id': '0001006289',
    'account_id': '0001009212',
    'custody_code': '064C500006',
    'available_power': 4884924031998,
    'buying_power': 4884924031998,
    'selling_power': 4884924024532,
    'max_buy_quantity': 135560840,
    'max_sell_quantity': 1000,
    'price': 36000.0,
    'error': None,
    'status_code': 200
}
</code></pre>

Dữ liệu có các thuộc tính:

| Tên thuộc tính      | Kiểu dữ liệu  | Mô tả                                                                            |
| ------------------- | ------------- | -------------------------------------------------------------------------------- |
| investor\_id        | str           | Mã định danh của nhà đầu tư (Investor ID).                                       |
| account\_id         | str           | Mã tài khoản giao dịch của nhà đầu tư.                                           |
| custody\_code       | str           | Mã lưu ký (Custody code) của tài khoản.                                          |
| available\_power    | float         | Tổng sức mua/bán khả dụng hiện tại (available trading power).                    |
| buying\_power       | float         | Sức mua còn lại có thể sử dụng cho giao dịch mua.                                |
| selling\_power      | float         | Sức bán còn lại có thể sử dụng cho giao dịch bán.                                |
| max\_buy\_quantity  | int           | Số lượng tối đa có thể mua tại mức giá hiện tại.                                 |
| max\_sell\_quantity | int           | Số lượng tối đa có thể bán tại mức giá hiện tại.                                 |
| price               | float         | Mức giá tham chiếu hoặc giá khớp hiện tại được sử dụng để tính toán sức mua/bán. |
| error               | str hoặc None | Thông tin lỗi (nếu có) khi lấy dữ liệu sức mua/bán.                              |
| status\_code        | int           | Mã code, nếu thành công là 200                                                   |

### 7.6.2. Phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

derivative_cap = orderbook_der.get_trading_power(ticker='41I1FB000', price=1975)
print(derivative_cap.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'investor_id': '0001006289',
    'account_id': '0001009212',
    'custody_code': '064C500006',
    'available_power': 3573140495626,
    'buying_power': 3573214662334,
    'selling_power': 3573140495626,
    'max_buy_quantity': 99608,
    'max_sell_quantity': 99542,
    'price': 1940.0,
    'error': None,
    'status_code': 200
}
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính      | Kiểu dữ liệu  | Mô tả                                                                            |
| ------------------- | ------------- | -------------------------------------------------------------------------------- |
| investor\_id        | str           | Mã định danh của nhà đầu tư (Investor ID).                                       |
| account\_id         | str           | Mã tài khoản giao dịch của nhà đầu tư.                                           |
| custody\_code       | str           | Mã lưu ký (Custody code) của tài khoản.                                          |
| available\_power    | float         | Tổng sức mua/bán khả dụng hiện tại (available trading power).                    |
| buying\_power       | float         | Sức mua còn lại có thể sử dụng cho giao dịch mua.                                |
| selling\_power      | float         | Sức bán còn lại có thể sử dụng cho giao dịch bán.                                |
| max\_buy\_quantity  | int           | Số lượng tối đa có thể mua tại mức giá hiện tại.                                 |
| max\_sell\_quantity | int           | Số lượng tối đa có thể bán tại mức giá hiện tại.                                 |
| price               | float         | Mức giá tham chiếu hoặc giá khớp hiện tại được sử dụng để tính toán sức mua/bán. |
| error               | str hoặc None | Thông tin lỗi (nếu có) khi lấy dữ liệu sức mua/bán.                              |
| status\_code        | int           | Mã code, nếu thành công là 200                                                   |


# 7.7. Lệnh

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Được sử dụng cho các hàm đặt lệnh, xem chi tiết lệnh, sửa lệnh, hủy lệnh, danh sách lệnh.

Mô tả các loại lệnh:

| Giá trị | Tên lệnh                       | Mô tả                                                                                                                               |
| ------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| LO      | Limit Order (Lệnh giới hạn)    | Lệnh mua/bán tại **mức giá cụ thể** hoặc tốt hơn. Hết ngày không khớp sẽ bị hủy.                                                    |
| MP      | Market Order (Lệnh thị trường) | Lệnh mua/bán **ngay tại giá thị trường tốt nhất hiện có**.                                                                          |
| MTL     | Market To Limit                | Lệnh thị trường nhưng nếu **không khớp hết**, phần còn lại chuyển thành lệnh giới hạn tại giá khớp cuối cùng.                       |
| ATO     | At The Open                    | Lệnh mua/bán **tại mức giá mở cửa**; chỉ có hiệu lực trong **phiên khớp lệnh định kỳ mở cửa**.                                      |
| ATC     | At The Close                   | Lệnh mua/bán tại **mức giá đóng cửa**; chỉ có hiệu lực trong phiên **khớp lệnh định kỳ đóng cửa**.                                  |
| MOK     | Match Or Kill                  | Lệnh thị trường, **phải khớp toàn bộ ngay lập tức**, nếu không khớp hết thì **bị hủy toàn bộ**.                                     |
| MAK     | Match And Kill                 | Lệnh thị trường, **khớp phần nào được phần đó**, phần còn lại **bị hủy**.                                                           |
| PLO     | Post Limit Order               | Lệnh giới hạn được **đặt sau phiên ATC**, chỉ được **khớp nếu có lệnh đối ứng** trong sổ lệnh. Áp dụng cho **phiên sau giờ (PLO)**. |

### 7.7.1. Đặt lệnh

* Cơ sở

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)

order = orderbook.place_order(
    ticker='HPG',
    side='buy',
    order_type='LO',
    quantity=1000,
    price=27000
)

print(order.summary())
```

**Tham số:**

| Tham số     | Kiểu dữ liệu | Bắt buộc | Mô tả                                                                                                     |
| ----------- | ------------ | -------- | --------------------------------------------------------------------------------------------------------- |
| ticker      | str          | Có       | Mã chứng khoán cần đặt lệnh (ví dụ: 'SSI').                                                               |
| side        | str          | Có       | Loại giao dịch: 'buy' (mua, long) hoặc 'sell' (bán, short).                                               |
| order\_type | str          | Có       | Loại lệnh đặt: 'LO', 'MP', 'MTL', 'ATO', 'ATC', 'MOK', 'MAK', 'PLO'. **Phái sinh sẽ không có PLO và MP**. |
| quantity    | int          | Có       | Khối lượng đặt lệnh.                                                                                      |
| price       | float        | Không    | Giá đặt lệnh (chỉ bắt buộc khi order\_type='LO').                                                         |

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': 131,
    'ticker': 'HPG',
    'side': 'Buy',
    'order_type': 'LO',
    'price': 27000.0,
    'quantity': 1000,
    'filled': 0,
    'avg_price': 0.0,
    'modified': '29/10/2025 10:57:02',
    'created': '29/10/2025 10:57:02',
    'status': 'Pending',
    'error': None,
    'status_code': 200
}
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Kiểu dữ liệu  | Mô tả                                         |
| -------------- | ------------- | --------------------------------------------- |
| id             | str           | Mã định danh của lệnh đặt.                    |
| side           | str           | Hướng giao dịch: NB = Mua, NS = Bán.          |
| ticker         | str           | Mã chứng khoán/phái sinh.                     |
| price          | float         | Giá đặt lệnh.                                 |
| quantity       | int           | Khối lượng đặt lệnh.                          |
| order\_type    | str           | Loại lệnh (ví dụ: LO, MP, ATC, ...).          |
| status         | str           | Trạng thái lệnh (new, filled, canceled, ...). |
| filled         | int           | Tổng khối lượng đã khớp.                      |
| avg\_price     | float         | Giá khớp trung bình của lệnh.                 |
| error          | str hoặc None | Thông tin lỗi (nếu có).                       |
| created        | datetime      | Thời điểm tạo lệnh.                           |
| modified       | datetime      | Thời điểm sửa đổi hoặc cập nhật lệnh.         |
| status\_code   | int           | Mã code, nếu thành công là 200                |

* Phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

derivative_order = orderbook_der.place_order(
    ticker='41I1FB000',
    side='buy',
    order_type='MTL',
    quantity=10
)

print(derivative_order.summary())
```

**Tham số:**

| Tham số                           | Kiểu dữ liệu | Bắt buộc                  | Mô tả                                                                                                                                                              |
| --------------------------------- | ------------ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| ticker                            | str          | Có                        | Mã phái sinh cần đặt lệnh (ví dụ: '41I1FB000').                                                                                                                    |
| side                              | str          | Có                        | Loại giao dịch: 'buy' (mua, long) hoặc 'sell' (bán, short).                                                                                                        |
| order\_type                       | str          | Có                        | Loại lệnh đặt: 'LO', 'MP', 'MTL', 'ATO', 'ATC', 'MOK', 'MAK', 'PLO'. **Phái sinh sẽ không có PLO và MP**.                                                          |
| quantity                          | int          | Có                        | Khối lượng đặt lệnh.                                                                                                                                               |
| price                             | float        | Không                     | Giá đặt lệnh (chỉ bắt buộc khi order\_type='LO').                                                                                                                  |
| take\_profit\_rate                | float        | Không (mặc định = 0.0)    | <p>Tỷ lệ chốt lời (%), tính trên giá vốn. Khi giá tăng đến mức tương ứng, hệ thống sẽ đặt lệnh chốt lời.</p><p>Yêu cầu nếu có: x>0</p>                             |
| stop\_loss\_rate                  | float        | Không (mặc định = 0.0)    | <p>Tỷ lệ cắt lỗ (%), tính trên giá vốn. Khi giá giảm đến mức tương ứng, hệ thống sẽ đặt lệnh cắt lỗ.</p><p>Yêu cầu nếu có: -1<=x<0</p>                             |
| take\_profit\_delta\_price        | float        | Không (mặc định bằng 0.0) | <p>Khoảng chênh lệch giá tuyệt đối (theo điểm giá) dùng để xác định mức chốt lời. Ưu tiên sử dụng nếu không dùng take\_profit\_rate.</p><p>Yêu cầu nếu có: x>0</p> |
| stop\_loss\_delta\_price          | float        | Không (mặc định bằng 0.0) | <p>Khoảng chênh lệch giá tuyệt đối (theo điểm giá) dùng để xác định mức cắt lỗ. Ưu tiên sử dụng nếu không dùng stop\_loss\_rate.</p><p>Yêu cầu nếu có: x>0</p>     |
| take\_profit\_order\_delta\_price | float        | Không (mặc định bằng 0.0) | Khoảng điểm tuỳ chỉnh của giá đặt so với giá kích hoạt, có thể âm hoặc dương.                                                                                      |
| stop\_loss\_order\_delta\_price   | float        | Không (mặc định bằng 0.0) | Khoảng điểm tuỳ chỉnh của giá đặt so với giá kích hoạt, có thể âm hoặc dương.                                                                                      |

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': 132,
    'ticker': '41I1FB000',
    'side': 'Buy',
    'order_type': 'MTL',
    'price': 27000.0,
    'quantity': 10,
    'filled': 0,
    'avg_price': 0.0,
    'modified': '29/10/2025 10:57:02',
    'created': '29/10/2025 10:57:02',
    'status': 'Pending',
    'error': None,
    'status_code': 200
}
```

Dữ liệu có các thuộc tính:

| Tên thuộc tính | Kiểu dữ liệu  | Mô tả                                         |
| -------------- | ------------- | --------------------------------------------- |
| id             | str           | Mã định danh của lệnh đặt.                    |
| side           | str           | Hướng giao dịch: NB = Mua, NS = Bán.          |
| ticker         | str           | Mã chứng khoán/phái sinh.                     |
| price          | float         | Giá đặt lệnh.                                 |
| quantity       | int           | Khối lượng đặt lệnh.                          |
| order\_type    | str           | Loại lệnh (ví dụ: LO, MP, ATC, ...).          |
| status         | str           | Trạng thái lệnh (new, filled, canceled, ...). |
| filled         | int           | Tổng khối lượng đã khớp.                      |
| avg\_price     | float         | Giá khớp trung bình của lệnh.                 |
| error          | str hoặc None | Thông tin lỗi (nếu có).                       |
| created        | datetime      | Thời điểm tạo lệnh.                           |
| modified       | datetime      | Thời điểm sửa đổi hoặc cập nhật lệnh.         |
| status\_code   | int           | Mã code, nếu thành công là 200                |

### 7.7.2. Chi tiết lệnh

* Cơ sở

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)

order_detail = orderbook.get_order_detail(order_id=161)
print(order_detail.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```python
{
    'id': 161,
    'ticker': 'HPG',
    'side': 'Buy',
    'order_type': 'LO',
    'price': 27000.0, 
    'quantity': 1000, 
    'filled': 0, 
    'avg_price': 0.0, 
    'modified': '29/10/2025 11:14:12', 
    'created': '29/10/2025 11:14:12', 
    'status': 'New', 
    'error': '', 
    'status_code': 200
}
```

* Phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

order_detail_der = orderbook_der.get_order_detail(order_id=86)
print(order_detail_der.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': 86, 
    'ticker': '41I1FB000', 
    'side': 'Buy', 
    'order_type': 'MTL', 
    'price': 0.0, 
    'quantity': 10, 
    'filled': 0, 
    'avg_price': 0.0, 
    'modified': '29/10/2025 11:18:45', 
    'created': '29/10/2025 11:18:45', 
    'status': 'Canceled', 
    'error': None, 
    'status_code': 200
}
```

### 7.7.3. Sửa lệnh (Chỉ sửa được với lệnh đặt là LO)

* Cơ sở

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)

modify_order = orderbook.modify_order(
    order_id=191,
    new_price = 26900,
    new_quantity=1000
)

print(modify_order.summary())
```

**Tham số:**

| Tên tham số   | Kiểu dữ liệu | Bắt buộc | Mô tả                                                            |
| ------------- | ------------ | -------- | ---------------------------------------------------------------- |
| order\_id     | int          | Có       | Mã định danh của lệnh cần sửa đổi.                               |
| new\_price    | float        | Có       | Giá mới muốn chỉnh sửa (chỉ áp dụng nếu là lệnh 'LO').           |
| new\_quantity | int          | Có       | Khối lượng mới muốn sửa của lệnh (chỉ áp dụng nếu là lệnh 'LO'). |

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': 191, 
    'ticker': 'HPG', 
    'side': 'Buy', 
    'order_type': 'LO', 
    'price': 26900.0, 
    'quantity': 1000, 
    'filled': 0,
    'avg_price': 0.0,
    'modified': '29/10/2025 11:23:54',
    'created': '29/10/2025 11:23:54',
    'status': 'Pending',
    'error': None,
    'status_code': 200
}
```

* Phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

derivative_modify = orderbook_der.modify_order(
    order_id=91,
    new_price=1945,
    new_quantity=5
)

print(derivative_modify.summary())
```

**Tham số:**

| Tên tham số   | Kiểu dữ liệu | Bắt buộc | Mô tả                                                            |
| ------------- | ------------ | -------- | ---------------------------------------------------------------- |
| order\_id     | int          | Có       | Mã định danh của lệnh cần sửa đổi.                               |
| new\_price    | float        | Có       | Giá mới muốn chỉnh sửa (chỉ áp dụng nếu là lệnh 'LO').           |
| new\_quantity | int          | Có       | Khối lượng mới muốn sửa của lệnh (chỉ áp dụng nếu là lệnh 'LO'). |

Ví dụ 1 hàm bị lỗi:

* Lỗi đặt lệnh hoặc sửa lệnh LO với mức giá đặt mua, bán lớn hơn mức giá trần

```json
{
    'id': None, 
    'ticker': None, 
    'side': 'Unknown', 
    'order_type': None, 
    'price': 0.0, 
    'quantity': 0, 
    'filled': 0, 
    'avg_price': 0.0, 
    'modified': None, 
    'created': None, 
    'status': None, 
    'error': '{
                    "status":400,
                    "code":"PRICE_MUST_LESS_THAN_OR_EQUAL_TO_CEILING_PRICE",
                    "message":"Price must be less than or equal to ceiling price"
               }',
     'status_code': 400
}
```

### 7.7.4. Hủy lệnh

* Cơ sở

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)

cancel_order = orderbook.cancel_order(order_id=661)
print(cancel_order.summary())
```

Mẫu kết quả trả ra là một dictionary chứa các thông tin sau:

```json
{
    'id': 661, 
    'ticker': 'SSI', 
    'side': 'Buy', 
    'order_type': 'LO', 
    'price': 36500.0, 
    'quantity': 500, 
    'filled': 0, 
    'avg_price': 0.0, 
    'modified': '29/10/2025 13:57:17', 
    'created': '29/10/2025 13:57:17', 
    'status': 'PendingCancel', 
    'error': None, 
    'status_code': 200
}
```

* Phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

cancel_order_derivative = orderbook_der.cancel_order(order_id=91)
print(cancel_order_derivative.summary())
```


# 7.8. Danh sách lệnh

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

* Cơ sở

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)

order_list = orderbook.get_list_orders(from_date='2025-10-09', to_date='2025-10-16')

for i in order_list:
    print(i.summary())
```

**Tham số:**

| Tên tham số | Kiểu dữ liệu | Bắt buộc | Mô tả                                                                                                               |
| ----------- | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------- |
| from\_date  | str          | Không    | Thời gian lọc ngày nhỏ nhất. Nếu không truyền, trả về tất cả các lệnh từ lệnh tạo từ ngày cũ nhất trong danh sách.  |
| to\_date    | str          | Không    | Thời gian lọc ngày lớn nhất. Nếu không truyền, trả về tất cả các lệnh từ lệnh tạo từ ngày mới nhất trong danh sách. |
| ticker      | str          | Không    | Lọc theo mã. Nếu không truyền, trả về tất cả các mã có trong các lệnh của danh sách.                                |
| status      | str          | Không    | Lọc theo trạng thái.  Nếu không truyền, trả về tất cả trạng thái hiện có trong danh sách                            |

Dữ liệu có các thuộc tính:

```json
{
    'id': 191, 
    'ticker': 'HPG', 
    'side': 'Buy', 
    'order_type': 'LO', 
    'price': 26900.0, 
    'quantity': 1000, 
    'filled': 0, 
    'avg_price': 0.0, 
    'modified': '29/10/2025 11:23:54', 
    'created': '29/10/2025 11:23:54', 
    'status': 'New', 
    'error': None, 
    'status_code': 200
}
```

* Phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

derivative_positions = orderbook_der.get_positions()
for i in derivative_positions:
    print(i.summary())
```

**Tham số:**

| Tên tham số | Kiểu dữ liệu | Bắt buộc | Mô tả                |
| ----------- | ------------ | -------- | -------------------- |
| from\_date  | str          | Không    | Thời gian lọc.       |
| to\_date    | str          | Không    | Thời gian lọc.       |
| ticker      | str          | Không    | Lọc theo mã.         |
| status      | str          | Không    | Lọc theo trạng thái. |


# 7.9. Lấy vị thế

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

* Cơ sở

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook = client_order.get_orderbook(
    account_id='0001009212',
    loan_id='13720'
)

positions = orderbook.get_positions()
for i in positions:
    print(i.summary())
```

**Tham số:**

| Tên tham số | Kiểu dữ liệu     | Bắt buộc | Mô tả                                                                                                                         |
| ----------- | ---------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| ticker      | string hoặc None | Không    | Mã chứng khoán cần lọc (ví dụ "HPG", "SSI"). Nếu không truyền, trả về tất cả mã.                                              |
| status      | string hoặc None | Không    | Trạng thái vị thế cần lọc. Có thể là "OPEN" (vị thế đang mở) hoặc "CLOSED" (vị thế đã đóng). Nếu không truyền, trả về tất cả. |
| side        | string hoặc None | Không    | Chiều giao dịch của vị thế. Có thể là "buy" hoặc "sell". Nếu không truyền, trả về cả hai chiều.                               |

Dữ liệu có các thuộc tính:

```json
{
    'id': 6858, 
    'ticker': 'STB', 
    'account_no': '0001009212', 
    'side': 'Buy', 
    'status': 'OPEN', 
    'quantity': 2700, 
    'cost_price': 28783.3333, 
    'market_price': 55600.0, 
    'accumulate_quantity': 2700, 
    'break_even_price': 28868.4237, 
    'realized_profit': 0.0, 
    'unrealized_profit': 72405000.09, 
    'created_date': '26/07/2024 14:23:04', 
    'error': None, 
    'status_code': 200
}
```

* Phái sinh

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

derivative_positions = orderbook_der.get_positions()
for i in derivative_positions:
    print(i.summary())
```

**Tham số:**

| Tên tham số | Kiểu dữ liệu     | Bắt buộc | Mô tả                                                                                                                         |
| ----------- | ---------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| ticker      | string hoặc None | Không    | Mã chứng khoán cần lọc (ví dụ "HPG", "SSI"). Nếu không truyền, trả về tất cả mã.                                              |
| status      | string hoặc None | Không    | Trạng thái vị thế cần lọc. Có thể là "OPEN" (vị thế đang mở) hoặc "CLOSED" (vị thế đã đóng). Nếu không truyền, trả về tất cả. |
| side        | string hoặc None | Không    | Chiều giao dịch của vị thế. Có thể là "buy" hoặc "sell". Nếu không truyền, trả về cả hai chiều.                               |

Dữ liệu có các thuộc tính:

```json
{
    'id': 10660, 
    'ticker': '41I1FB000', 
    'account_no': '0001009212',
    'side': 'Sell', 
    'status': 'OPEN', 
    'quantity': 2, 
    'cost_price': 2006.675, 
    'market_price': 1940.9, 
    'accumulate_quantity': 6, 
    'break_even_price': 2006.2189,
    'realized_profit': -39795000.0,
    'unrealized_profit': 13155000.0,
    'created_date': '27/10/2025 13:16:41',
    'error': None,
    'status_code': 200
}
```


# 7.10. Đóng deal (đối với phái sinh)

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

```python
username_dnse = 'REPLACE_WITH_YOUR_DNSE_USERNAME'
password_dnse = 'REPLACE_WITH_YOUR_DNSE_PASSWORD'

client_order = client.FiinQuantConnector(
    broker='DNSE',
    username=username_dnse,
    password=password_dnse,
    smart_otp=True
).login()

orderbook_der = client_order.get_derivative_orderbook(
    account_id='0001009212',
    loan_id='2278'
)

close_deal = orderbook_der.close_deal(deal_id="10680")
print(close_deal.summary())
```

* Lưu ý: **deal\_id** lấy ở các hàm vị thế phái sinh.

Dữ liệu có các thuộc tính:

```json
{
    'id': 266, 
    'ticker': '41I1FB000', 
    'side': 'Sell', 
    'price': 1805.1, 
    'quantity': 1, 
    'fill_quantity': 0, 
    'average_price': 0.0, 
    'loan_package_id': 2278, 
    'initial_rate': 0.0, 
    'created_date': '29/10/2025 14:43:55', 
    'error': None, 
    'status_code': 200
}
```


# 8. Danh sách chỉ số TA


# 8.1. Trend Indicators (Chỉ báo xu hướng)

### 8.1.1. **EMA (Exponential Moving Average)**

> **EMA** là đường trung bình di động được tính toán với trọng số, **gán mức độ quan trọng cao hơn cho dữ liệu giá gần hơn**. EMA phản ứng nhanh hơn với những thay đổi giá cả, giúp nhà đầu tư nắm bắt xu hướng thị trường một cách kịp thời.

```python
def ema(column: pandas.core.series.Series, window: int)
```

**Tham số**

| Tên tham số | Ý nghĩa                                                 | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------- | ------------- | ---------------- |
| column      | Cột dữ liệu (series) chứa các giá trị để tính toán EMA. | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính EMA.      | int           |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
df['ema_5'] = fi.ema(df['close'], window = 5)
print(df)
```

### **8.1.2. SMA (Simple Moving Average)**

> SMA là đường trung bình di động đơn giản, là một chỉ báo được tính bằng cách **lấy trung bình cộng của giá trong một khoảng thời gian nhất định**.

```python
def sma(column: pandas.core.series.Series, window: int)
```

**Tham số**

| Tên tham số | Mô tả                                                   | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------- | ------------- | ---------------- |
| column      | Cột dữ liệu (series) chứa các giá trị để tính toán SMA. | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính SMA.      | int           |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
df['sma_5'] = fi.sma(df['close'], window = 5)
print(df)
```

### **8.1.3. SMMA (**&#x53;moothed Moving Averag&#x65;**)**

> Chỉ báo SMMA (Smoothed Moving Average) là **đường trung bình động trơn**, một công cụ phân tích kỹ thuật giúp làm mịn các biến động giá để xác định xu hướng dài hạn hiệu quả hơn. Nó sử dụng dữ liệu giá trong quá khứ để làm mượt các biến động ngắn hạn, tạo ra một đường xu hướng rõ ràng và ít nhiễu hơn. **SMMA** được tính toán dựa trên một khoảng thời gian dài hơn và có trọng số lớn hơn cho các dữ liệu giá gần đây hơn so với **đường trung bình di động đơn giản (SMA)**.&#x20;

```python
def smma(column: pandas.core.series.Series, window: int)
```

**Tham số**

| Tên tham số | Mô tả                                                    | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | -------------------------------------------------------- | ------------- | ---------------- |
| column      | Cột dữ liệu (series) chứa các giá trị để tính toán SMMA. | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính SMMA.      | int           |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
df['smma_20'] = fi.smma(df['close'], window = 20)
print(df)
```

### **8.1.4. WMA (Weighted Moving Average)**

> WMA là đường trung bình tỷ trọng tuyến tính. Chỉ báo này sẽ nhạy cảm hơn và có biến động sát hơn so với các biến động của giá thị trường. WMA sử dụng trọng số khác nhau cho mỗi giá trị trong chuỗi dữ liệu. Trong đó, các trọng số cao nhất sẽ được gán với giá trị mới nhất và giảm dần cho đến giá trị cũ nhất. Chính đặc tính này đã khiến đường WMA trở lên nhạy cảm hơn và “có dữ liệu mịn hơn” so với các đường trung bình động SMA hay EMA.

```python
def wma(column: pandas.core.series.Series, window: int)
```

**Tham số**

| Tên tham số | Mô tả                                                   | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------- | ------------- | ---------------- |
| column      | Cột dữ liệu (series) chứa các giá trị để tính toán WMA. | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính WMA.      | int           |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
df['wma'] = fi.wma(df['close'], window = 14)
print(df)
```

### **8.1.5. MACD (Moving Average Convergence Divergence)**

> MACD là một trong những công cụ phân tích kỹ thuật được sử dụng rộng rãi bởi các nhà giao dịch. MACD giúp đo lường động lượng, hướng và sức mạnh của một xu hướng giá.
>
> Cấu tạo:
>
> * Đường MACD: Sự khác nhau giữa đường EMA ngắn hạn (thường là 12 ngày) và đường EMA dài hạn (thường là 26 ngày).
> * Đường tín hiệu (Signal): Đường EMA của đường MACD (thường là 9 ngày).
> * Biểu đồ MACD (Histogram): Sự khác nhau giữa đường MACD và đường tín hiệu.

```python
def macd(column: pandas.core.series.Series, window_slow: int = 26, window_fast: int = 12)

def macd_signal(column: pandas.core.series.Series, window_slow: int = 26, window_fast: int = 12, window_sign: int = 9)

def macd_diff(column: pandas.core.series.Series, window_slow: int = 26, window_fast: int = 12, window_sign: int = 9)
```

**Tham số**

| Tên tham số  | Mô tả                                                                      | Kiểu dữ liệu  | Giá trị mặc định |
| ------------ | -------------------------------------------------------------------------- | ------------- | ---------------- |
| column       | Cột dữ liệu (series) chứa các giá trị để tính toán MACD.                   | pandas.Series |                  |
| window\_slow | Số lượng điểm dữ liệu sử dụng cho đường EMA dài hạn trong tính toán MACD.  | int           | 26               |
| window\_fast | Số lượng điểm dữ liệu sử dụng cho đường EMA ngắn hạn trong tính toán MACD. | int           | 12               |
| window\_sign | Số lượng điểm dữ liệu sử dụng cho đường EMA trong tính toán MACD Signal.   | int           | 9                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['macd'] = fi.macd(df['close'], window_fast=12, window_slow=26)
df['macd_signal'] = fi.macd_signal(df['close'], window_fast=12, window_slow=26, window_sign=9)
df['macd_diff'] = fi.macd_diff(df['close'], window_fast=12, window_slow=26, window_sign=9)
print(df)
```

### **8.1.6. ADX (ADXIndicator)**

> ADX là công cụ chỉ báo giao động xác định độ mạnh yếu của xu hướng. Người ta thường dùng công cụ này để xác định thị trường đang đi ngang (thị trường sideway) hay đã bắt đầu xu hướng chưa. Ban đầu, chỉ báo này được sử dụng phổ biến trong thị trường hàng hoá, sau này được mở rộng sang nhiều thị trường tài chính khác như: Chứng khoán, forex, tiền điện tử.

```python
def adx(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14)

def adx_neg(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14)

def adx_pos(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14)
```

**Tham số**

| Tên tham số | Mô tả                                                             | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ----------------------------------------------------------------- | ------------- | ---------------- |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán ADX . | pandas.Series |                  |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán ADX.   | pandas.Series |                  |
| close       | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán ADX.   | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính ADX.                | int           | 14               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['adx'] = fi.adx(df['high'], df['low'], df['close'], window=14)
df['adx_neg'] = fi.adx_neg(df['high'], df['low'], df['close'], window=14)
df['adx_pos'] = fi.adx_pos(df['high'], df['low'], df['close'], window=14)
print(df)
```

### **8.1.7. PSAR (Parabolic Stop and Reverse)**

PSAR là một chỉ báo kỹ thuật do J. Welles Wilder Jr. phát triển, được sử dụng để xác định xu hướng giá và điểm đảo chiều trong giao dịch. PSAR nằm dưới giá khi xu hướng tăng và nằm trên giá khi xu hướng giảm, giúp nhà giao dịch xác định các mức hỗ trợ hoặc kháng cự. Khi giá vượt qua PSAR, xu hướng có thể đảo chiều. Chỉ báo này dễ sử dụng, đặc biệt hiệu quả trong thị trường có xu hướng mạnh, nhưng có thể tạo tín hiệu nhiễu trong thị trường đi ngang.

```python
def psar(self, high: pd.Series, low: pd.Series, close: pd.Series, step: float = 0.02, max_step: float = 0.2)
```

**Tham số:**

| Tên tham số | Mô tả                                                                                                                                                                                                                                                                         | Kiểu dữ liệu  | Mặc định |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------- |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất.                                                                                                                                                                                                                                | pandas.Series |          |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất.                                                                                                                                                                                                                               | pandas.Series |          |
| close       | Cột dữ liệu chứa các giá trị cột giá đóng cửa.                                                                                                                                                                                                                                | pandas.Series |          |
| step        | Hệ số gia tốc (Acceleration Factor - AF) khởi tạo trong quá trình tính toán.Step càng nhỏ -> PSAR sẽ phản ứng chậm hơn với thay đổi giá, phù hợp cho các thị trường ít biến động.Step lớn hơn -> PSAR nhạy hơn, dễ bắt kịp các thay đổi nhưng cũng có thể tạo tín hiệu nhiễu. | float         | 0.02     |
| max\_step   | Giá trị tối đa mà hệ số gia tốc (AF) có thể đạt được.                                                                                                                                                                                                                         | float         | 0.2      |

Ví dụ:

<pre class="language-python"><code class="lang-python">fi = client.FiinIndicator()
<strong>df['psar'] = fi.psar(df['high'], df['low'], df['close'], step=0.02, max_step=0.2)
</strong><strong>print(df)
</strong></code></pre>

### **8.1.8. Ichimoku (Ichimoku Kinko Hyo)**

Ichimoku là một chỉ báo kỹ thuật do Goichi Hosoda phát triển, giúp đánh giá xu hướng, mức hỗ trợ, kháng cự và cung cấp tín hiệu mua bán trong một biểu đồ duy nhất. Chỉ báo gồm năm thành phần chính: Tenkan-sen, Kijun-sen, Senkou Span A, Senkou Span B, và Chikou Span, tạo thành "đám mây" (Kumo) thể hiện động lực thị trường. Ichimoku đặc biệt hiệu quả trong các thị trường có xu hướng rõ ràng, giúp nhà giao dịch đưa ra quyết định dựa trên sự cân bằng giá.

```python
def ichimoku_a(self, high: pd.Series, low: pd.Series, close: pd.Series, window1: int = 9, window2: int = 26, window3: int = 52) -> pd.Series: ...
def ichimoku_b(self, high: pd.Series, low: pd.Series, close: pd.Series, window1: int = 9, window2: int = 26, window3: int = 52) -> pd.Series: ...
def ichimoku_base_line(self, high: pd.Series, low: pd.Series, close: pd.Series, window1: int = 9, window2: int = 26, window3: int = 52) -> pd.Series: ...
def ichimoku_conversion_line(self, high: pd.Series, low: pd.Series, close: pd.Series, window1: int = 9, window2: int = 26, window3: int = 52) -> pd.Series: ...
def ichimoku_lagging_line(self, high: pd.Series, low: pd.Series, close: pd.Series,
    window1: int = 9, window2: int = 26, window3: int = 52) -> pd.Series: ...
```

**Tham số**

| Tham số | Mô tả                                                                                                                  | Kiểu dữ liệu  | Mặc định |
| ------- | ---------------------------------------------------------------------------------------------------------------------- | ------------- | -------- |
| high    | Cột dữ liệu chứa các giá trị cột giá cao nhất.                                                                         | pandas.Series |          |
| low     | Cột dữ liệu chứa các giá trị cột giá thấp nhất.                                                                        | pandas.Series |          |
| close   | Cột chứa dữ liệu giá đóng cửa.                                                                                         | pandas.Series |          |
| window1 | Số lượng điểm dữ liệu sử dụng cho đường Conversion Line (Tenkan-sen).                                                  | int           | 9        |
| window2 | Số lượng điểm dữ liệu sử dụng cho đường Base Line (Kijun-sen) và để dịch các đường như Chikou Span và Senkou Span A/B. | int           | 26       |
| window3 | Số lượng điểm dữ liệu sử dụng cho đường Senkou Span B.                                                                 | int           | 52       |

Ví dụ:

```python
fi = client.FiinIndicator()
df['senkou_span_a'] = fi.ichimoku_a(df['high'], df['low'], df['close'], window1 = 9, window2 = 26, window3 = 52)
df['senkou_span_b'] = fi.ichimoku_b(df['high'], df['low'], df['close'], window1 = 9, window2 = 26, window3 = 52)
df['kijun_sen'] = fi.ichimoku_base_line(df['high'], df['low'], df['close'], window1 = 9, window2 = 26, window3 = 52) 
df['tenkan_sen'] = fi.ichimoku_conversion_line(df['high'], df['low'], df['close'], window1 = 9, window2 = 26, window3 = 52)
print(df)
```

### **8.1.9. CCI (Commodity Channel Index)**

CCI là một chỉ báo kỹ thuật được Donald Lambert phát triển dùng để đo lường độ lệch của giá so với giá trị trung bình trong một khoảng thời gian, giúp xác định điều kiện quá mua hoặc quá bán. Khi CCI vượt ngưỡng 100, giá có thể đang quá mua, và khi dưới -100, giá có thể đang quá bán. Chỉ báo này phù hợp để phát hiện xu hướng mới hoặc cảnh báo sự đảo chiều tiềm năng.

```python
def cci(self, high: pd.Series, low: pd.Series, close: pd.Series, window: int = 20, constant: float = 0.015) -> pd.Series: ...
```

**Tham số:**

| Tham số  | Mô tả                                                                         | Kiểu dữ liệu  | Mặc định |
| -------- | ----------------------------------------------------------------------------- | ------------- | -------- |
| high     | Cột dữ liệu chứa các giá trị cột giá cao nhất.                                | pandas.Series |          |
| low      | Cột dữ liệu chứa các giá trị cột giá thấp nhất.                               | pandas.Series |          |
| close    | Cột dữ liệu chứa các giá trị cột giá đóng cửa.                                | pandas.Series |          |
| window   | Số lượng điểm dữ liệu sử dụng cho đường SMA và Mean Deviation.                | int           | 20       |
| constant | Hằng số chuẩn hóa để đảm bảo giá trị CCI dao động trong một phạm vi xác định. | float         | 0.015    |

Ví dụ:

```python
fi = client.FiinIndicator()
df['cci'] = fi.cci(df['high'], df['low'], df['close'], window = 20, constant = 0.015)
print(df)
```

### **8.1.10. Aroon**

Aroon là một chỉ báo kỹ thuật do Tushar Chande phát triển, dùng để đo lường sức mạnh của xu hướng và xác định sự bắt đầu hoặc kết thúc của xu hướng. Chỉ báo gồm hai thành phần chính: Aroon-Up (theo dõi đỉnh cao nhất) và Aroon-Down (theo dõi đáy thấp nhất) trong một khoảng thời gian nhất định. Giá trị dao động từ 0 đến 100, với mức cao cho thấy xu hướng mạnh và mức thấp cho thấy sự yếu dần của xu hướng. Aroon đặc biệt hữu ích trong việc phát hiện các giai đoạn tích lũy hoặc đảo chiều trên thị trường.

<pre class="language-python"><code class="lang-python"><strong>def aroon(self, high: pd.Series, low: pd.Series, window: int = 25) -> pd.Series: ...
</strong>def aroon_up(self, high: pd.Series, low: pd.Series, window: int = 25) -> pd.Series: ... 
def aroon_down(self, high: pd.Series, low: pd.Series, window: int = 25) -> pd.Series: ...
</code></pre>

**Tham số:**

| Tham số | Mô tả                                                          | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | -------------------------------------------------------------- | ------------- | ---------------- |
| high    | Cột dữ liệu chứa các giá trị cột giá cao nhất.                 | pandas.Series |                  |
| low     | Cột dữ liệu chứa các giá trị cột giá thấp nhất.                | pandas.Series |                  |
| window  | Số lượng điểm dữ liệu sử dụng cho đường SMA và Mean Deviation. | int           | 25               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['aroon'] = fi.aroon(df['high'], df['low'], window: int = 25)
df['aroon_up'] = fi.aroon_up(df['high'], df['low'], window: int = 25)
df['aroon_down'] = fi.aroon_down(df['high'], df['low'], window: int = 25)
print(df)
```

### **8.1.11. Zig Zag**

Zig Zag là một chỉ báo phổ biến giúp lọc bỏ những biến động giá nhỏ để loại bỏ nhiễu dữ liệu và nhấn mạnh xu hướng. Các nhà giao dịch thường sử dụng Zig Zag để xác nhận xu hướng, xác định ngưỡng hỗ trợ và kháng cự tiềm năng và phát hiện mô hình. Chỉ báo này được hình thành bằng cách xác định các điểm cao và thấp cục bộ quan trọng theo thứ tự xen kẽ và kết nối chúng bằng các đường thẳng, bỏ qua tất cả các điểm dữ liệu khác khỏi đầu ra của chúng. Có một số cách để tính toán các điểm dữ liệu của Zig Zag và các điều kiện theo đó hướng của nó thay đổi. Tập lệnh này sử dụng các điểm xoay làm điểm dữ liệu, là các giá trị cao nhất hoặc thấp nhất trong một số thanh xác định trước và sau chúng. Hướng chỉ đảo ngược khi một điểm xoay mới hình thành lệch khỏi điểm Zig Zag cuối cùng theo hướng ngược lại với một lượng lớn hơn hoặc bằng một tỷ lệ phần trăm được chỉ định.

<pre class="language-python"><code class="lang-python"><strong>def zigzag(self, high: pd.Series, low: pd.Series, dev_threshold: float = 5.0, depth: int = 10) -> pd.Series: ...
</strong></code></pre>

**Tham số:**

| Tham số        | Mô tả                                                                      | Kiểu dữ liệu  | Giá trị mặc định |
| -------------- | -------------------------------------------------------------------------- | ------------- | ---------------- |
| high           | Cột dữ liệu chứa các giá trị cột giá cao nhất.                             | pandas.Series |                  |
| low            | Cột dữ liệu chứa các giá trị cột giá thấp nhất.                            | pandas.Series |                  |
| dev\_threshold | Độ lệch phần trăm tối thiểu từ một điểm trước khi đường ​ZigZag đổi hướng. | float         | 5.0              |
| depth          | Số thanh cần thiết để phát hiện điểm pivot.                                | int           | 10               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['zigzag'] = fi.zigzag(df['high'], df['low'], dev_threshold = 5.0, depth = 10)
print(df)
```

### **8.1.12.** DC (Donchian Channel)

**Donchian Channel (DC)**, hay còn gọi là **Kênh Donchian**, là một chỉ báo phân tích kỹ thuật được phát triển bởi Richard Donchian, người được mệnh danh là "Cha đẻ của giao dịch theo xu hướng" (Trend Following). Chỉ báo này được sử dụng để đo lường **biến động** và xác định **phạm vi giá** tối đa và tối thiểu của một tài sản trong một khoảng thời gian cụ thể (N kỳ).

<pre class="language-python"><code class="lang-python"><strong>def donchian_channel_hband(self, high: pd.Series, low: pd.Series, close: pd.Series, window: int = 20, offset: int = 0) -> pd.Series: ...
</strong>def donchian_channel_lband(self, high: pd.Series, low: pd.Series, close: pd.Series, window: int = 20, offset: int = 0) -> pd.Series: ...
def donchian_channel_mband(self, high: pd.Series, low: pd.Series, close: pd.Series, window: int = 20, offset: int = 0) -> pd.Series: ...
def donchian_channel_pband(self, high: pd.Series, low: pd.Series, close: pd.Series, window: int = 20, offset: int = 0) -> pd.Series: ...
def donchian_channel_wband(self, high: pd.Series, low: pd.Series, close: pd.Series, window: int = 20, offset: int = 0) -> pd.Series: ...
</code></pre>

**Tham số:**

| Tham số | Mô tả                                                | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | ---------------------------------------------------- | ------------- | ---------------- |
| high    | Cột dữ liệu chứa các giá trị cột giá cao nhất.       | pandas.Series |                  |
| low     | Cột dữ liệu chứa các giá trị cột giá thấp nhất.      | pandas.Series |                  |
| close   | Cột dữ liệu chứa các giá trị cột giá đóng cửa.       | pandas.Series |                  |
| window  | Số lượng phiên được dùng để tính toán kênh Donchian. | int           | 20               |
| offset  | Số phiên dịch chuyển (nếu muốn trễ tín hiệu).        | int           | 0                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['dc_high'] = fi.donchian_channel_hband(df["high"], df["low"], df["close"], window=20, offset=0)
df['dc_low'] = fi.donchian_channel_lband(df["high"], df["low"], df["close"], window=20, offset=0)
df['dc_mid'] = fi.donchian_channel_mband(df["high"], df["low"], df["close"], window=20, offset=0)
df['dc_percentage'] = fi.donchian_channel_pband(df["high"], df["low"], df["close"], window=20, offset=0)
df['dc_width'] = fi.donchian_channel_wband(df["high"], df["low"], df["close"], window=20, offset=0)
print(df)
```

### **8.1.13.** Vortex Indicator

**Vortex Indicator (VI)**, hay **Chỉ báo Lốc xoáy**, là một chỉ báo kỹ thuật dựa trên xu hướng, được phát triển bởi Etienne Botes và Douglas Siepman vào năm 2010. Nó được thiết kế để **xác định sự bắt đầu của một xu hướng mới** hoặc **xác nhận hướng đi** của xu hướng hiện tại.

Chỉ báo Vortex bao gồm hai đường dao động chính:

* **+VI (Vortex Positive)**: Đo lường sức mạnh của **xu hướng tăng** (chuyển động đi lên).
* **-VI (Vortex Negative)**: Đo lường sức mạnh của **xu hướng giảm** (chuyển động đi xuống).

```python
def vortex_indicator_pos(high: pandas.Series,  low: pandas.Series,  close: pandas.Series, window: int = 14) -> pd.Series: ...
def vortex_indicator_neg(high: pandas.Series,  low: pandas.Series,  close: pandas.Series, window: int = 14) -> pd.Series: ...
def vortex_indicator_diff(high: pandas.Series,  low: pandas.Series,  close: pandas.Series, window: int = 14) -> pd.Series: ...
```

**Tham số:**

| Tham số | Mô tả                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | ----------------------------------------------- | ------------- | ---------------- |
| high    | Cột dữ liệu chứa các giá trị cột giá cao nhất.  | pandas.Series |                  |
| low     | Cột dữ liệu chứa các giá trị cột giá thấp nhất. | pandas.Series |                  |
| close   | Cột dữ liệu chứa các giá trị cột giá đóng cửa.  | pandas.Series |                  |
| window  | Số phiên dùng để tính trung bình (chu kỳ).      | int           | 14               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['vi+'] = fi.vortex_indicator_pos(df["high"], df["low"], df["close"], window=14)
df['vi+'] = fi.vortex_indicator_neg(df["high"], df["low"], df["close"], window=14)
df['vi_diff'] = fi.vortex_indicator_diff(df["high"], df["low"], df["close"], window=14)
print(df)
```

### **8.1.14.** TEMA (Triple Exponential Moving Average)

**Triple Exponential Moving Average (TEMA)**, hay **Đường Trung bình Động Hàm mũ Bậc ba**, là một chỉ báo kỹ thuật được phát triển bởi Patrick G. Mulloy vào năm 1994. Mục tiêu chính của TEMA là **giảm thiểu độ trễ (lag)** vốn có trong các đường trung bình động truyền thống như Simple Moving Average (SMA) và Exponential Moving Average (EMA), giúp chỉ báo phản ứng nhanh hơn với sự thay đổi của giá.

Mặc dù có tên là "Triple" (Bậc ba), TEMA không chỉ đơn giản là áp dụng ba lần EMA. Thay vào đó, nó sử dụng một công thức độc đáo để kết hợp EMA đơn, EMA kép (Double EMA - DEMA), và EMA bậc ba nhằm loại bỏ độ trễ.

```python
def tema(close: pandas.Series, window: int = 9)
```

**Tham số:**

| Tham số | Mô tả                                          | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | ---------------------------------------------- | ------------- | ---------------- |
| close   | Cột dữ liệu chứa các giá trị cột giá đóng cửa. | pandas.Series |                  |
| window  | Số phiên dùng để tính trung bình động.         | int           | 9                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['tema_9'] = fi.tema(df["close"], window=9)
print(df)
```

### **8.1.15.** DEMA (Double Exponential Moving Average)

**DEMA** là viết tắt của **Double Exponential Moving Average** (Đường Trung bình Động Hàm mũ Kép), là một chỉ báo phân tích kỹ thuật được phát triển bởi Patrick G. Mulloy vào năm 1994.

Mục tiêu chính của DEMA là **giảm thiểu độ trễ (lag)** vốn có trong đường trung bình động hàm mũ tiêu chuẩn (EMA), giúp đường chỉ báo bám sát hành động giá hơn và cung cấp tín hiệu sớm hơn.

```python
def dema(close: pandas.Series, window: int = 9)
```

**Tham số:**

| Tham số | Mô tả                                          | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | ---------------------------------------------- | ------------- | ---------------- |
| close   | Cột dữ liệu chứa các giá trị cột giá đóng cửa. | pandas.Series |                  |
| window  | Số phiên dùng để tính trung bình động.         | int           | 9                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['dema_9'] = fi.dema(df["close"], window=9)
print(df)
```

### **8.1.16.** ZLEMA (Zero Lag Exponential Moving Average)

**ZLEMA** là viết tắt của **Zero Lag Exponential Moving Average** (Đường Trung bình Động Hàm mũ Không Độ trễ). Đây là một chỉ báo phân tích kỹ thuật được thiết kế nhằm mục đích loại bỏ hoặc giảm thiểu tối đa độ trễ (lag) vốn có của các đường trung bình động truyền thống như **SMA** (Simple Moving Average) và **EMA** (Exponential Moving Average).

ZLEMA được phát triển để phản ánh sự thay đổi của giá nhanh hơn, giúp nhà giao dịch xác định sự đảo chiều hoặc tiếp diễn xu hướng một cách kịp thời hơn.

```python
def zlema(column: pandas.Series, window: int = 14)
```

**Tham số:**

| Tham số | Mô tả                                                    | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | -------------------------------------------------------- | ------------- | ---------------- |
| column  | Cột dữ liệu (thường là giá đóng cửa) để tính toán ZLEMA. | pandas.Series |                  |
| window  | Số phiên dùng để tính trung bình động.                   | int           | 14               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['zlema_9'] = fi.zlema(df["close"], window=14)
print(df)
```

### **8.1.17.** Jurik Moving Average

**Jurik Moving Average (JMA)** là một chỉ báo phân tích kỹ thuật tiên tiến, được phát triển bởi nhà toán học **Mark Jurik**. JMA được coi là một trong những đường trung bình động (Moving Average) mạnh mẽ nhất vì nó được thiết kế để giải quyết hai vấn đề lớn của các MA truyền thống (như SMA và EMA): **độ trễ (lag)** và **nhiễu giá (noise)**.

Mục tiêu chính của JMA là bám sát giá một cách chặt chẽ nhất có thể nhưng vẫn giữ được độ mượt mà.

```python
def jma(price: pandas.Series, length: int = 7, phase: int = 50, power: int = 2)
```

**Tham số:**

| Tham số | Mô tả                                                                                             | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | ------------------------------------------------------------------------------------------------- | ------------- | ---------------- |
| price   | Chuỗi giá (thường là giá đóng cửa).                                                               | pandas.Series |                  |
| length  | Độ dài chu kỳ tính toán JMA.                                                                      | int           | 7                |
| phase   | Điều chỉnh độ nhạy (từ -100 đến +100): giá trị dương khiến JMA tiến gần giá hơn, âm làm mượt hơn. | int           | 50               |
| power   | Mức độ “phản ứng” của bộ lọc (power cao → phản ứng nhanh hơn).                                    | int           | 2                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['jma'] = fi.jma(df["close"], length=7, phase=50, power=2)
print(df)
```

### **8.1.18.** Hull Moving Average

**Hull Moving Average (HMA)** là một chỉ báo đường trung bình động (Moving Average) được thiết kế bởi Alan Hull vào năm 2005. Mục đích của HMA là giảm thiểu độ trễ (lag) của các MA truyền thống như SMA và EMA, đồng thời vẫn giữ được độ mượt cần thiết để lọc bỏ nhiễu giá.

HMA đạt được sự cân bằng này thông qua một công thức tính toán phức tạp.

```python
def hma(close: pandas.Series, period: int = 9)
```

**Tham số:**

| Tham số | Mô tả                                       | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | ------------------------------------------- | ------------- | ---------------- |
| close   | Chuỗi giá đầu vào (thường là giá đóng cửa). | pandas.Series |                  |
| period  | Số chu kỳ tính HMA (>= 2).                  | int           | 9                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['hma'] = fi.hma(df["close"], period=9)
print(df)
```

### **8.1.19.** Fractal Adaptive Moving Average

**Fractal Adaptive Moving Average (FRAMA)** là một loại đường trung bình động (Moving Average) thông minh được phát triển bởi **John Ehlers**. Điểm độc đáo của FRAMA là khả năng **tự động điều chỉnh hệ số làm mượt (smoothing factor)** dựa trên **kích thước Fractal (Fractal Dimension)** của hành động giá.

FRAMA giải quyết được vấn đề nan giải của các MA truyền thống: làm thế nào để vừa phản ứng nhanh với các xu hướng mạnh (giảm độ trễ) vừa lọc nhiễu hiệu quả trong thị trường đi ngang (tăng độ mượt).

```python
def frama(df: pandas.DataFrame, window: int = 16)
```

**Tham số:**

| Tham số | Mô tả                                    | Kiểu dữ liệu     | Giá trị mặc định |
| ------- | ---------------------------------------- | ---------------- | ---------------- |
| df      | Dataframe đầu vào                        | pandas.DataFrame |                  |
| window  | Số phiên dùng để tính FRAMA (phải chẵn). | int              | 16               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['frama'] = fi.frama(df, window=16)
print(df)
```

### **8.1.20.** Arnaud Legoux Moving Average

**Arnaud Legoux Moving Average (ALMA)** là một chỉ báo đường trung bình động (Moving Average) được phát triển bởi Arnaud Legoux và Dimitrios Kouzis-Loukas nhằm giải quyết nhược điểm cố hữu của các MA truyền thống: sự đánh đổi giữa **độ trễ (lag)** và **độ mượt (smoothness)**.

ALMA nổi bật vì nó có thể giảm thiểu độ trễ một cách hiệu quả mà vẫn duy trì độ mượt cao, giúp nhà giao dịch xác định xu hướng nhanh hơn và giảm tín hiệu nhiễu.

```python
def alma(column: pandas.Series, period: int = 9, offset: float = 0.85, sigma: float = 6)
```

**Tham số:**

| Tham số | Mô tả                                          | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | ---------------------------------------------- | ------------- | ---------------- |
| column  | Chuỗi giá đầu vào (thường là Close).           | pandas.Series |                  |
| period  | Số phiên dùng để tính ALMA.                    | int           | 9                |
| offset  | Vị trí trọng tâm (0 → đầu, 1 → cuối).          | float         | 0.85             |
| sigma   | Độ rộng của hàm Gaussian (điều chỉnh độ mượt). | float         | 6.0              |

Ví dụ:

```python
fi = client.FiinIndicator()
df['alma'] = fi.alma(df["close"], period=9, offset=0.85, sigma=6.0)
print(df)
```

### **8.1.21.** TRIX

TRIX là chỉ báo động lượng được tính bằng **tỷ lệ thay đổi (%ROC)** của **Triple EMA** (EMA của EMA của EMA).\
Chỉ báo giúp xác định xu hướng trung hạn và loại bỏ nhiễu bằng cách làm mượt dữ liệu ba lần liên tiếp.

```python
def trix(column: pd.Series, window: int = 18) -> pd.Series: ...
```

**Tham số:**

| Tham số | Mô tả                                                     | Kiểu dữ liệu  | Giá trị mặc định |
| ------- | --------------------------------------------------------- | ------------- | ---------------- |
| column  | Chuỗi giá đầu vào (thường là Close).                      | pandas.Series |                  |
| period  | Số lượng điểm dữ liệu sử dụng trong phép tính Triple EMA. | int           | 18               |

Ví dụ:

```python
fi = client.FiinIndicator()
df["trix_18"] = fi.trix(df["close"], period=18)
print(df)
```


# 8.2. Momentum Indicators (Chỉ báo động lượng)

### 8.**2.1. RSI (Relative Strength Index)**

> RSI là một chỉ báo đo lường tốc độ và biên độ của biến động giá gần đây để đánh giá liệu một tài sản đang bị mua quá nhiều (overbought) hay bán quá nhiều (oversold).
>
> RSI được tính toán dựa trên giá đóng cửa trong một khoảng thời gian nhất định (thường là 14 ngày).
>
> Chỉ số này dao động trong khoảng từ 0 đến 100.
>
> * RSI trên 70: Là vùng quá mua, tài sản có thể đã tăng giá quá nhanh và có khả năng điều chỉnh giảm.
> * RSI dưới 30: Là vùng quá bán, tài sản có thể đã giảm giá quá sâu và có khả năng phục hồi.

```python
def rsi(column: pandas.core.series.Series, window: int = 14)
```

**Tham số**

| Tên tham số | Mô tả                                                   | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------- | ------------- | ---------------- |
| column      | Cột dữ liệu (series) chứa các giá trị để tính toán RSI. | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính RSI.      | int           | 14               |

**Ví dụ:**

```python
fi = client.FiinIndicator()
df['rsi'] = fi.rsi(df['close'], window=14)
print(df)
```

### 8.**2.2. RSI Divergence (Relative Strength Index Divergence)**

> **RSI divergence (RSI phân kỳ)** là sự di chuyển ngược chiều giữa giá tài sản và chỉ báo RSI, là một tín hiệu cảnh báo sớm rằng xu hướng hiện tại có thể sắp đảo chiều. Nó cho thấy sự thay đổi trong động lượng thị trường trước khi sự thay đổi đó xuất hiện rõ ràng trong biểu đồ giá. **RSI divergence** được coi là một công cụ mạnh mẽ, giúp nhà giao dịch xác định các tín hiệu đảo chiều tiềm năng, nhưng nên kết hợp với các chỉ báo khác để tăng độ chính xác.

```python
def rsi_divergence(column: pandas.core.series.Series, fast_window: int = 5, slow_window: int = 14)
```

**Tham số**

| Tên tham số  | Mô tả                                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ------------ | --------------------------------------------------------------- | ------------- | ---------------- |
| column       | Cột dữ liệu (series) chứa các giá trị để tính toán RSI phân kỳ. | pandas.Series |                  |
| fast\_window | Số lượng điểm dữ liệu sử dụng trong phép tính RSI nhanh.        | int           | 5                |
| slow\_window | Số lượng điểm dữ liệu sử dụng trong phép tính RSI chậm.         | int           | 14               |

**Ví dụ:**

```python
fi = client.FiinIndicator()
df['rsi_divergence'] = fi.rsi_divergence(df['close'], fast_window=5, slow_window=14)
print(df)
```

### **8.2.3. Stochastic**

> Stochastic Oscillator (Chỉ báo Dao động ngẫu nhiên) là một công cụ phân tích kỹ thuật hiệu quả, giúp đánh giá động lượng và khả năng đảo chiều của giá, xác định vùng mua/bán tiềm năng trên thị trường.
>
> Cấu tạo:
>
> * %K: Đường này so sánh giá đóng cửa hiện tại của chứng khoán với phạm vi giá cao nhất và thấp nhất trong một khoảng thời gian nhất định. Trên 80: Cho thấy chứng khoán có thể quá mua, khả năng điều chỉnh giá xuống. Dưới 20: Cho thấy chứng khoán có thể quá bán, khả năng phục hồi giá.
> * %D: Đường SMA của %K, giúp làm mượt mà các biến động ngắn hạn.

> Cả %K và %D đều dao động trong khoảng từ 0 đến 100.

```python
def stoch(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14)
```

```python

def stoch_signal(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14, smooth_window: int = 3)
```

**Tham số**

| Tên tham số    | Mô tả                                                                                             | Kiểu dữ liệu  | Giá trị mặc định |
| -------------- | ------------------------------------------------------------------------------------------------- | ------------- | ---------------- |
| low            | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán Stochastic.                           | pandas.Series |                  |
| high           | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán Stochastic.                            | pandas.Series |                  |
| close          | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán Stochastic.                            | pandas.Series |                  |
| window         | Số lượng điểm dữ liệu sử dụng trong phép tính Stochastic.                                         | int           | 14               |
| smooth\_window | Số lượng điểm dữ liệu sử dụng trong phép tính Stochastic Signal bằng cách lấy SMA của Stochastic. | int           | 3                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['stoch'] = fi.stoch(df['high'], df['low'], df['close'], window=14)
df['stoch_signal'] = fi.stoch_signal(df['high'], df['low'], df['close'], window=14, smooth_window=3)
print(df)
```

### **8.2.4.** AO (Awesome Oscillator)

> **Awesome Oscillator (AO)** là một chỉ báo kỹ thuật về **động lượng thị trường** (market momentum) được phát triển bởi nhà phân tích tài chính **Bill Williams**. Chỉ báo này được trình bày dưới dạng một biểu đồ **histogram** (biểu đồ cột) dao động **xung quanh đường Zero**. AO so sánh động lượng ngắn hạn (SMA5) với động lượng dài hạn (SMA34) để đánh giá sức mạnh của xu hướng hiện tại và dự đoán các khả năng đảo chiều.

```python
def awesome_oscillator(high: pandas.Series, low: pandas.Series, window1: int = 5, window2: int = 34)
```

**Tham số**

| Tên tham số | Mô tả                                                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------------------------------- | ------------- | ---------------- |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán Awesome Oscillator.  | pandas.Series |                  |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán Awesome Oscillator. | pandas.Series |                  |
| window1     | Số kỳ dùng để tính trung bình ngắn hạn (thường là 5).                           | int           | 5                |
| window2     | Số kỳ dùng để tính trung bình dài hạn (thường là 34).                           | int           | 34               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['ao'] = fi.awesome_oscillator(df['high'], df['low'], window1=5, window2=34)
print(df)
```

### **8.2.5.** PPO (The Percentage Price Oscillator)

> **Percentage Price Oscillator (PPO)** là một chỉ báo động lượng kỹ thuật (technical momentum indicator) đo lường **sự khác biệt phần trăm** giữa hai đường trung bình động (Moving Averages).
>
> Chỉ báo này rất giống với chỉ báo **MACD (Moving Average Convergence Divergence)**, nhưng thay vì đo lường sự khác biệt tuyệt đối (giá trị tuyệt đối) giữa hai đường trung bình động, PPO biểu thị sự khác biệt đó dưới dạng **phần trăm** của đường trung bình động dài hạn.

```python
def ppo(close: pandas.Series, window_slow: int = 26, window_fast: int = 12, window_sign: int = 9)
def ppo_hist(close: pandas.Series, window_slow: int = 26, window_fast: int = 12, window_sign: int = 9)
def ppo_signal(close: pandas.Series, window_slow: int = 26, window_fast: int = 12, window_sign: int = 9)
```

**Tham số**

| Tên tham số  | Mô tả                                            | Kiểu dữ liệu  | Giá trị mặc định |
| ------------ | ------------------------------------------------ | ------------- | ---------------- |
| close        | Cột giá đóng cửa của tài sản dùng để tính PPO.   | pandas.Series |                  |
| window\_slow | Số kỳ của EMA chậm (thường là 26).               | int           | 26               |
| window\_fast | Số kỳ của EMA nhanh (thường là 12).              | int           | 12               |
| window\_sign | Số kỳ dùng để tính đường tín hiệu (Signal line). | int           | 9                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['ppo'] = fi.ppo(df['close'], window_slow=26, window_fast=12, window_sign=9)
df['ppo_hist'] = fi.ppo_hist(df['close'], window_slow=26, window_fast=12, window_sign=9)
df['ppo_signal'] = fi.ppo_signal(df['close'], window_slow=26, window_fast=12, window_sign=9)
print(df)
```

### **8.2.6.** ROC (Rate of Change)

> **Rate of Change (ROC)**, hay còn gọi là **Tỷ lệ Thay đổi**, là một **chỉ báo động lượng (momentum oscillator)** quan trọng trong phân tích kỹ thuật.
>
> Nó đo lường **tốc độ** mà giá của một tài sản đang thay đổi bằng cách xác định **phần trăm thay đổi** của giá trong một khoảng thời gian xác định (n kỳ) so với giá hiện tại. ROC giúp nhà giao dịch đánh giá sức mạnh của xu hướng và dự đoán các khả năng đảo chiều.

```python
def roc(close: pandas.Series, window: int = 9)
```

**Tham số**

| Tên tham số | Mô tả                                                      | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ---------------------------------------------------------- | ------------- | ---------------- |
| close       | Cột giá đóng cửa của tài sản dùng để tính tốc độ thay đổi. | pandas.Series |                  |
| window      | Số kỳ lùi về trước để so sánh thay đổi giá.                | int           | 9                |

Ví dụ:

```python
fi = client.FiinIndicator()
df['roc'] = fi.roc(df['close'], window=9)
print(df)
```

### **8.2.7.** UO (Ultimate Oscillator)

> **Ultimate Oscillator (UO)** là một **chỉ báo động lượng kỹ thuật** được phát triển bởi Larry Williams vào năm 1976. Thiết kế cốt lõi của nó là đo lường động lượng đồng thời trên **ba khung thời gian khác nhau**, giúp giảm thiểu sự biến động và số lượng tín hiệu phân kỳ sai thường thấy ở các bộ dao động chỉ dùng một chu kỳ.
>
> Chỉ báo UO dao động trong khoảng từ **0 đến 100** và chủ yếu được sử dụng để xác định các điều kiện **quá mua/quá bán** cũng như tạo ra các tín hiệu đảo chiều dựa trên **phân kỳ**.

```python
def ultimate_oscillator(high: pandas.Series, low: pandas.Series, close: pandas.Series, window1: int = 7, window2: int = 14, window3: int = 28, weight1: float = 4.0, weight2: float = 2.0, weight3: float = 1.0)
```

**Tham số**

| Tên tham số | Mô tả                                                        | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------------ | ------------- | ---------------- |
| high        | Cột giá cao nhất trong phiên, dùng để tính biên độ dao động. | pandas.Series |                  |
| low         | Cột giá thấp nhất trong phiên.                               | pandas.Series |                  |
| close       | Cột giá đóng cửa của tài sản.                                | pandas.Series |                  |
| window1     | Số kỳ ngắn hạn để tính trung bình (thường là 7).             | int           | 7                |
| window2     | Số kỳ trung hạn (thường là 14).                              | int           | 14               |
| window3     | Số kỳ dài hạn (thường là 28).                                | int           | 28               |
| weight1     | Trọng số cho chu kỳ ngắn hạn.                                | float         | 4.0              |
| weight2     | Trọng số cho chu kỳ trung hạn.                               | float         | 2.0              |
| weight3     | Trọng số cho chu kỳ dài hạn.                                 | float         | 1.0              |

Ví dụ:

```python
fi = client.FiinIndicator()
df['uo'] = fi.ultimate_oscillator(df["high"], df["low"], df["close"], window1=7, window2=14, window3=28, weight1=4.0, weight2=2.0, weight3=1.0)
print(df)
```

### **8.2.8.** Williams %R

> **Williams %R (Williams Percentage Range)** là một **chỉ báo động lượng kỹ thuật** được phát triển bởi Larry Williams. Nó là một bộ dao động có giới hạn, tương tự như Stochastic Oscillator, được sử dụng chủ yếu để xác định các điều kiện **quá mua (overbought)** và **quá bán (oversold)** trên thị trường.
>
> Chỉ báo này đo lường vị trí giá đóng cửa hiện tại so với phạm vi giá cao nhất và thấp nhất trong một khoảng thời gian nhất định (thường là 14 kỳ).

```python
def williams_r(high: pandas.Series, low: pandas.Series, close: pandas.Series, lbp: int = 14)
```

**Tham số**

| Tên tham số | Mô tả                                                        | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------------ | ------------- | ---------------- |
| high        | Cột giá cao nhất trong phiên, dùng để tính biên độ dao động. | pandas.Series |                  |
| low         | Cột giá thấp nhất trong phiên.                               | pandas.Series |                  |
| close       | Cột giá đóng cửa của tài sản.                                | pandas.Series |                  |
| lbp         | Số kỳ dùng để tính biên độ giá (lookback period).            | int           | 14               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['WilliamsR'] = fi.williams_r(df["high"], df["low"], df["close"], lbp=14)
print(df)
```

### **8.2.9.** PMO (Price Momentum Oscillator)

> **PMO (Price Momentum Oscillator)** là chỉ báo động lượng được phát triển bởi **Carl Swenlin**, dùng để đo **tốc độ thay đổi giá** tương tự như MACD nhưng được **làm mượt hai lần (double-smoothed)** nhằm giảm nhiễu và phản ánh **sức mạnh xu hướng rõ ràng hơn**.
>
> PMO được xây dựng dựa trên tỷ lệ thay đổi giá (%ROC), sau đó áp dụng **EMA hai lần** để tính ra giá trị dao động mượt mà hơn, giúp nhà đầu tư xác định các **tín hiệu mua – bán** dựa trên giao cắt giữa PMO và đường tín hiệu (Signal Line).

```python
def pmo(close: pandas.Series, smoothing: int = 35, double_smoothing: int = 20, signal: int = 10)
```

**Tham số**

| Tên tham số       | Mô tả                                      | Kiểu dữ liệu  | Giá trị mặc định |
| ----------------- | ------------------------------------------ | ------------- | ---------------- |
| close             | Cột giá đóng cửa của tài sản.              | pandas.Series |                  |
| smoothing         | Số kỳ làm mượt đầu tiên cho %ROC (EMA 1).  | int           | 35               |
| double\_smoothing | Số kỳ làm mượt thứ hai cho PMO (EMA 2).    | int           | 20               |
| signal            | Số kỳ dùng để tính đường tín hiệu của PMO. | int           | 10               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['pmo'] = fi.pmo(df["close"], smoothing=35, double_smoothing=20, signal=10)
print(df)
```

### **8.2.10.** MOM (Momentum)

> **Momentum** là chỉ báo đo **tốc độ thay đổi giá** trong một khoảng thời gian nhất định. Nó cho biết giá hiện tại **cao hơn hoặc thấp hơn bao nhiêu** so với giá của *n* phiên trước.
>
> Chỉ báo này giúp xác định **sức mạnh xu hướng** và **các tín hiệu đảo chiều** khi động lượng tăng hoặc giảm đột ngột.

```python
def mom(close: pandas.Series, period: int = 10, relative: bool = False)
```

**Tham số**

| Tên tham số | Mô tả                                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | --------------------------------------------------------------- | ------------- | ---------------- |
| close       | Cột giá đóng cửa của tài sản.                                   | pandas.Series |                  |
| period      | Số phiên dùng để so sánh                                        | int           | 10               |
| relative    | Nếu True → tính Momentum %, nếu False → tính Momentum tuyệt đối | bool          | False            |

Ví dụ:

```python
fi = client.FiinIndicator()
df['mom'] = fi.mom(df["close"], period=10, relative=False)
print(df)
```

### **8.2.11.** (APO) Absolute Price Oscillator

> **Absolute Price Oscillator (APO)** là một chỉ báo động lượng (momentum oscillator) trong phân tích kỹ thuật được sử dụng để đo lường **sự khác biệt tuyệt đối** giữa hai đường trung bình động hàm mũ (EMA) có chu kỳ khác nhau.
>
> APO về cơ bản là **giống hệt** với đường **MACD** (Moving Average Convergence Divergence) về mặt công thức, ngoại trừ việc MACD thường đi kèm với Đường Tín hiệu (Signal Line) và Biểu đồ Histogram, còn APO thì thường chỉ tập trung vào sự khác biệt tuyệt đối giữa hai đường EMA.

```python
def apo(price: pandas.Series, fast_period: int = 10, slow_period: int = 20)
```

**Tham số**

| Tên tham số  | Mô tả                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ------------ | ----------------------------------------------- | ------------- | ---------------- |
| price        | Chuỗi giá (thường là giá đóng cửa) của tài sản. | pandas.Series |                  |
| fast\_period | Số phiên tính EMA nhanh                         | int           | 10               |
| slow\_period | Số phiên tính EMA chậm                          | int           | 20               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['apo'] = fi.apo(df["close"], fast_period=10, slow_period=20)
print(df)
```

### **8.2.12.** Coppock Curve

> **Coppock Curve** (còn được gọi là Tỷ lệ Thay đổi Khối lượng Tích lũy - Coppock Guide) là một chỉ báo phân tích kỹ thuật theo đà (momentum indicator) được thiết kế để nhận diện các **điểm mua vào dài hạn** đối với các chỉ số thị trường chứng khoán.
>
> Trong đó:
>
> * **ROC short**: Tốc độ thay đổi giá 11 kỳ
> * **ROC long**: Tốc độ thay đổi giá 14 kỳ
> * **WMA**: Trung bình động có trọng số (Weighted Moving Average) với độ dài 10
>
> Coppock Curve thường được dùng để nhận diện tín hiệu:
>
> * **Mua** khi Coppock từ âm → dương (cross up 0)
> * **Cảnh báo giảm** khi Coppock tạo đỉnh và giảm lại

```python
def coppock_curve(close: pd.Series, roc_short: int = 11, roc_long: int = 14, wma_length: int = 10) -> pd.Series: ...
```

**Tham số**

| Tên tham số | Mô tả                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ----------------------------------------------- | ------------- | ---------------- |
| close       | Chuỗi giá (thường là giá đóng cửa) của tài sản. | pandas.Series |                  |
| roc\_short  | Chu kỳ ROC ngắn hạn                             | int           | 11               |
| roc\_long   | Chu kỳ ROC dài hạn                              | int           | 14               |
| wma\_length | Chu kỳ WMA của tổng ROC                         | int           | 10               |

Ví dụ:

```python
fi = client.FiinIndicator()
df["coppock_curve"] = fi.coppock_curve(close=df["close"], roc_short=11, roc_long=14, wma_length=10)
print(df)
```


# 8.3. Volatility Indicators (Chỉ báo biến động)

### 8.**3.1. Bollinger Bands**

> Bollinger Bands (Dải Bollinger) là một công cụ phân tích kỹ thuật được phát triển bởi John Bollinger vào những năm 1980. Bollinger Bands giúp đo lường sự biến động (volatility) của giá và xác định mức giá cao/thấp tiềm năng trong một xu hướng.
>
> Cấu tạo:
>
> * Dải trung tâm (Centerline): Đường trung bình động (thường là đường SMA 20 ngày) của giá.
> * Dải trên (Upper Band): Số lần chênh lệch chuẩn nhất định (thường là 2) tính trên đường trung tâm, được cộng thêm vào giá trị của đường trung tâm.
> * Dải dưới (Lower Band): Số lần chênh lệch chuẩn nhất định (thường là 2) tính trên đường trung tâm, được trừ đi khỏi giá trị của đường trung tâm.
>
> Các tính năng thêm:
>
> * Độ rộng dải (Bollinger Band Width): Chỉ số đo lường độ biến động (volatility) của giá, được tính từ khoảng cách giữa dải trên và dải dưới của Bollinger Bands và chia cho dải trung tâm.
> * Tín hiệu "nén" giá (Bollinger Squeeze): Chỉ báo cho biết khi độ rộng của dải Bollinger Bands (Bollinger Band Width) thu hẹp đáng kể, cho thấy biến động thị trường giảm mạnh, và một cú bứt phá (breakout) sắp xảy ra.

```python
def bollinger_mband(column: pandas.core.series.Series, window: int = 20)
def bollinger_hband(column: pandas.core.series.Series, window: int = 20, window_dev: int = 2)
def bollinger_lband(column: pandas.core.series.Series, window: int = 20, window_dev: int = 2)
def bollinger_wband(column: pandas.core.series.Series, window: int = 20, window_dev: int = 2)
def bollinger_squeeze(column: pandas.core.series.Series, window: int = 20, window_dev: int = 2, squeeze_mode: Literal['dynamic', 'percentile'] = "dynamic", dynamic_thresold: float = 0.9, percentile_thresold: int = 10)
```

**Tham số**

| Tên tham số          | Mô tả                                                                                                                                                                                                                                                                                                         | Kiểu dữ liệu  | Giá trị mặc định |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ---------------- |
| column               | Cột dữ liệu chứa các giá trị để tính toán Bollinger Bands.                                                                                                                                                                                                                                                    | pandas.Series |                  |
| window               | Số lượng điểm dữ liệu sử dụng trong phép tính Bollinger Bands.                                                                                                                                                                                                                                                | int           | 20               |
| window\_dev          | Số lượng độ lệch chuẩn sử dụng để tính toán khoảng cách các dải của Bollinger Bands.                                                                                                                                                                                                                          | int           | 2                |
| squeeze\_mode        | Kiểu "nén giá": **percentile** (Thị trường đang ở trạng thái squeeze khi **BBW** rơi xuống **nhỏ hơn ngưỡng percentile** nhất định trong lịch sử (ví dụ: 10%, 15%)) hoặc **dynamic** **(ngưỡng nén được điều chỉnh linh hoạt** theo **mức trung bình động** của BB Width thay vì cố định bằng **percentile**) | str           | 'dynamic'        |
| dynamic\_thresold    | Hệ số kiểu "nén giá" linh động                                                                                                                                                                                                                                                                                | float         | 0.9              |
| percentile\_thresold | Hệ số kiểu "nén giá" percentile                                                                                                                                                                                                                                                                               | int           | 10               |

Ví dụ

<pre class="language-python"><code class="lang-python">fi = client.FiinIndicator()
df['bollinger_mband'] = fi.bollinger_mband(df['close'], window=20)
<strong>df['bollinger_hband'] = fi.bollinger_hband(df['close'], window=20, window_dev=2)
</strong><strong>df['bollinger_lband'] = fi.bollinger_lband(df['close'], window=20, window_dev=2)
</strong>df['bollinger_wband'] = fi.bollinger_wband(df['close'], window=20, window_dev=2)
df['bollinger_squeeze'] = fi.bollinger_squeeze(df['close'], window=20, window_dev=2, squeeze_mode='dynamic', dynamic_thresold=0.9)
print(df)
</code></pre>

### **8.3.2. Supertrend**

> Supertrend (siêu xu hướng) là một công cụ phân tích kỹ thuật được phát triển bởi nhà đầu tư Olivier Seban vào năm 2010. Supertrend sử dụng kết hợp các yếu tố như giá cả ATR (Average True Range - Biên độ dao động trung bình thực) và xu hướng hiện tại để xác định xu hướng chính của thị trường và các điểm đảo chiều tiềm năng.

```python
def supertrend(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14, multiplier: float = 3.0)


def supertrend_hband(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14, multiplier: float = 3.0)


def supertrend_lband(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14, multiplier: float = 3.0)
```

**Tham số:**

| Tên tham số | Mô tả                                                                        | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ---------------------------------------------------------------------------- | ------------- | ---------------- |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán Supertrend.       | pandas.Series |                  |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán Supertrend.      | pandas.Series |                  |
| close       | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán Supertrend.       | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính Supertrend.                    | int           | 14               |
| multiplier  | Hệ số nhân dùng để điều chỉnh độ rộng của chỉ báo Supertrend so với mức giá. | float         | 3.0              |

Ví dụ:

```python
fi = client.FiinIndicator()
df['supertrend'] = fi.supertrend(df['high'], df['low'], df['close'], window=14)
df['supertrend_hband'] = fi.supertrend_hband(df['high'], df['low'], df['close'], window=14)
df['supertrend_lband'] = fi.supertrend_lband(df['high'], df['low'], df['close'], window=14)
print(df)
```

### **8.3.3. ATR (AverageTrueRange)**

> ATR là khoảng dao động trung bình thực tế. Đây là chỉ báo để đo lường những biến động của giá trong một khoảng thời gian nhất định.
>
> Chỉ báo được giới thiệu trong cuốn sách “Tư tưởng mới trong Hệ thống kỹ thuật Giao dịch” của J. Welles Wilder Jr vào năm 1978. Thông qua chỉ báo, nhà đầu tư có thể dự đoán mức giá dao động trong tương lai. Nhờ đó, nhà đầu tư có cơ sở để đặt điểm cắt lỗ và chốt lời hợp lý.

```python
def atr(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, window: int = 14)
```

**Tham số:**

| Tên tham số | Mô tả                                                            | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ---------------------------------------------------------------- | ------------- | ---------------- |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán ATR.  | pandas.Series |                  |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán ATR. | pandas.Series |                  |
| close       | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán ATR.  | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính ATR.               | int           | 14               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['atr'] = fi.atr(df['high'], df['low'], df['close'], window=14)
print(df)
```

### **8.3.4.** Realized Volatility

> **Realized Volatility (annualized)** là chỉ báo đo lường **mức độ biến động thực tế của giá** dựa trên lợi suất logarit trong một khoảng thời gian nhất định.
>
> Chỉ báo này thường được **annualize (quy đổi theo năm)** để phản ánh biến động trung bình năm, giúp nhà đầu tư đánh giá **mức rủi ro hoặc độ ổn định của tài sản**.

```python
def realized_volatility(close: pandas.Series, window: int = 14, trading_days: int = 252)
```

**Tham số:**

| Tên tham số   | Mô tả                                                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ------------- | ------------------------------------------------------------------------------- | ------------- | ---------------- |
| close         | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán realized volatility. | pandas.Series |                  |
| window        | Số phiên (ngày) được dùng để tính trung bình phương sai (rolling window).       | int           | 14               |
| trading\_days | Số ngày giao dịch trong năm, dùng để annualize biến động.                       | int           | 252              |

Ví dụ:

```python
fi = client.FiinIndicator()
df['rv'] = fi.realized_volatility(df["close"], window=14, trading_days=252)
print(df)
```

### **8.3.5.** Keltner Channels

> **Kênh Keltner (Keltner Channels)** là các đường bao xung quanh dựa trên biến động giá có thể ở trên hoặc dưới **đường trung bình động lũy thừa (EMA)**. **Chỉ báo Keltner** sử dụng chỉ báo **Khoảng dao động trung bình thực tế (ATR)** để đặt khoảng cách kênh. Thông thường, chỉ báo **kênh Keltner** sẽ sử dụng 2 đường **ATR** ở trên và dưới đường **EMA 20 ngày**. Đường này sẽ điều khiển hướng trong khi đường **ATR** sẽ điều khiển độ rộng của kênh.
>
> Chỉ báo **kênh Keltner** là chỉ báo theo sau xu hướng thường được dùng để tìm tín hiệu **đảo chiều xu hướng** thông qua việc **phá kênh** hay dựa vào hướng của kênh. Chỉ báo này cũng được sử dụng để xác định vùng **quá mua** và **quá bán** khi thị trường không có xu hướng.

```python
def kc_midline(close: pandas.Series, high: pandas.Series, low: pandas.Series, ema_window: int = 20, atr_window: int = 10, atr_mult: float = 2)
def kc_upper(close: pandas.Series, high: pandas.Series, low: pandas.Series, ema_window: int = 20, atr_window: int = 10, atr_mult: float = 2, band_style: Literal['avg_true_range', 'true_range', 'range'] = "avg_true_range")
def kc_lower(close: pandas.Series, high: pandas.Series, low: pandas.Series, ema_window: int = 20, atr_window: int = 10, atr_mult: float = 2, band_style: Literal['avg_true_range', 'true_range', 'range'] = "avg_true_range")
```

**Tham số:**

| Tên tham số | Mô tả                                                                                                                                   | Kiểu dữ liệu  | Giá trị mặc định   |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ------------------ |
| close       | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán các kênh Keltner.                                                            | pandas.Series |                    |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán các kênh Keltner.                                                            | pandas.Series |                    |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán các kênh Keltner.                                                           | pandas.Series |                    |
| ema\_window | Số phiên (ngày) được dùng để tính đường trung bình động lũy thừa (EMA).                                                                 | int           | 20                 |
| atr\_window | Số phiên (ngày) được dùng để tính khoảng dao động trung bình thực tế (ATR).                                                             | int           | 10                 |
| atr\_mult   | Số nhân với khoảng dao động trung bình thực tế (ATR) để tính kênh trên và kênh dưới.                                                    | float         | 2.0                |
| band\_style | Kiểu dải là 1 trong 3 giá trị 'avg\_true\_range': Khoảng dao động thực tế trung bình, 'true\_range': Phạm vi thực thế, 'range': Phạm vi | str           | 'avg\_true\_range' |

Ví dụ:

```python
fi = client.FiinIndicator()
df["kc_midline"] = fi.kc_midline(df["close"], df["high"], df["low"], ema_window = 20, atr_window = 10, atr_mult = 2)
df["kc_upper"] = fi.kc_upper(df["close"], df["high"], df["low"], ema_window = 20, atr_window = 10, atr_mult = 2, band_style = 'avg_true_range')
df["kc_lower"] = fi.kc_lower(df["close"], df["high"], df["low"], band_style = 'avg_true_range')
print(df)
```

Trực quan bằng biểu đồ

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FBinvGmz6yoqZdQ6QyisE%2FKeltner_Channels.png?alt=media&amp;token=7bac3deb-71d6-4ebd-82aa-ac9e3f6b21aa" alt=""><figcaption><p>Keltner Channels với kiểu dải <strong>Khoảng dao động thực tế trung bình</strong></p></figcaption></figure>

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FHWiEYeayLCPRM4fZ8Jsr%2FKeltner_Channels_True_Range.png?alt=media&amp;token=4fcfdd1a-ecff-4e6b-b4da-fb68bf3b56a0" alt=""><figcaption><p>Keltner Channels với kiểu dải <strong>Phạm vi thực tế</strong></p></figcaption></figure>

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FNO04vXc7ispDZCdX5ZYE%2FKeltner_Channels_Range.png?alt=media&amp;token=97fa2b06-9486-447d-bf1f-ba4f926cac82" alt=""><figcaption><p>Keltner Channels với kiểu dải <strong>Phạm vi</strong></p></figcaption></figure>

Source code:

```python
import pandas as pd
import matplotlib.pyplot as plt
import mplfinance as mpf

from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

df = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["MWG"],
    fields=["open","high","low","close"],
    adjusted=True,
    by="1d",
    from_date="2024-10-20",
    lasted=True
).get_data()

fi = client.FiinIndicator()
df["kc_midline"] = fi.kc_midline(df["close"], df["high"], df["low"])
df["kc_upper"] = fi.kc_upper(df["close"], df["high"], df["low"])
df["kc_lower"] = fi.kc_lower(df["close"], df["high"], df["low"])

# ----- 1️⃣ Chuyển đổi timestamp sang datetime -----
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M')

# Đặt timestamp làm index để phù hợp với mplfinance
df = df.set_index('timestamp')

# ----- 3️⃣ Vẽ biểu đồ -----
# Tạo đối tượng “additional plot” cho đường trend line
add_plots = [
    mpf.make_addplot(df["kc_midline"], color='blue', width=1.5, label='Basis'),
    mpf.make_addplot(df["kc_upper"], color='blue', width=1.5, label='Upper'),
    mpf.make_addplot(df["kc_lower"], color='blue', width=1.5, label='Lower')
]

mpf.plot(
    df,
    type='candle',
    style='yahoo',
    addplot=add_plots,
    title='Candlestick Chart with Keltner Channels',
    ylabel='Price',
    ylabel_lower='Volume',
    datetime_format='%Y-%m-%d',
    tight_layout=True,
    figratio=(16, 8)
)

plt.show()


```


# 8.4. Volume Indicators (Chỉ báo khối lượng)

### 8.**4.1. MFI (Money Flow Index)**

> MFI là chỉ số phản ánh sức mạnh dòng tiền của một cổ phiếu trong một khoản thời gian nhất định, được phân tích dựa vào khối lượng giao dịch. Khoảng thời gian được xem xét theo ngày, tuần tháng, và thường tính toán theo giá trị 14 giai đoạn.

```python
def mfi(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, volume: pandas.core.series.Series, window: int = 14)
```

**Tham số**

| Tên tham số | Mô tả                                                                   | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ----------------------------------------------------------------------- | ------------- | ---------------- |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán MFI.         | pandas.Series |                  |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán MFI.        | pandas.Series |                  |
| close       | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán MFI.         | pandas.Series |                  |
| volume      | Cột dữ liệu chứa các giá trị cột khối lượng giao dịch để tính toán MFI. | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính MFI.                      | int           | 14               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['mfi'] = fi.mfi(df['high'], df['low'], df['close'], df['volume'], window=14)
print(df)
```

### **8.4.2. OBV (On Balance Volume)**

> OBV là chỉ báo khối lượng có chức năng đo lường khối lượng giao dịch tích lũy qua các phiên, từ đó cho thấy cổ phiếu đang có xu hướng được mua hay bán. Nếu phiên hôm nay là một phiên tăng giá thì khối lượng sẽ được cộng thêm vào chỉ số OBV. Ngược lại, khối lượng sẽ được trừ ra khi hôm nay là một phiên giao dịch giảm điểm.

```python
def obv(column: pandas.core.series.Series, volume: pandas.core.series.Series)
```

**Tham số**

| Tên tham số | Mô tả                                                                   | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ----------------------------------------------------------------------- | ------------- | ---------------- |
| column      | Cột dữ liệu (series) chứa các giá trị về giá để tính toán OBV.          | pandas.Series |                  |
| volume      | Cột dữ liệu chứa các giá trị cột khối lượng giao dịch để tính toán OBV. | pandas.Series |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
df['obv'] = fi.obv(df['close'], df['volume'])
print(df)
```

### **8.4.3. VWAP (Volume Weighted Adjusted Price)**

> **VWAP** là giá trung bình theo trọng số khối lượng, giá trung bình của một cổ phiếu tính theo tổng khối lượng giao dịch. VWAP được sử dụng để tính giá trung bình của một cổ phiếu trong một khoảng thời gian.
>
> Giá bình quân gia quyền theo khối lượng giúp so sánh giá hiện tại của cổ phiếu với giá chuẩn, giúp nhà đầu tư dễ dàng quyết định thời điểm tham gia và thoát khỏi thị trường. Ngoài ra, VWAP có thể hỗ trợ các nhà đầu tư xác định cách đầu tư của họ đối với một cổ phiếu và thực hiện chiến lược giao dịch phù hợp vào đúng thời điểm.

```python
def vwap(high: pandas.core.series.Series, low: pandas.core.series.Series, close: pandas.core.series.Series, volume: pandas.core.series.Series, window: int = 14)
```

**Tham số:**<br>

| Tên tham số | Mô tả                                                                    | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ------------------------------------------------------------------------ | ------------- | ---------------- |
| high        | Cột dữ liệu chứa các giá trị cột giá cao nhất để tính toán VWAP.         | pandas.Series |                  |
| low         | Cột dữ liệu chứa các giá trị cột giá thấp nhất để tính toán VWAP.        | pandas.Series |                  |
| close       | Cột dữ liệu chứa các giá trị cột giá đóng cửa để tính toán VWAP.         | pandas.Series |                  |
| volume      | Cột dữ liệu chứa các giá trị cột khối lượng giao dịch để tính toán VWAP. | pandas.Series |                  |
| window      | Số lượng điểm dữ liệu sử dụng trong phép tính VWAP.                      | int           | 14               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['vwap'] = fi.vwap(df['high'], df['low'], df['close'], df['volume'], window=14)
print(df)
```

### **8.4.4.** Volume Profile

> **Volume Profile** là công cụ phân tích kỹ thuật hiển thị phân bố khối lượng giao dịch tại các mức giá khác nhau trong một giai đoạn cụ thể.
>
> Chỉ báo giúp nhà đầu tư nhận biết các vùng giá có **khối lượng giao dịch lớn** (vùng giá quan trọng, hỗ trợ/kháng cự) và **vùng giá ít quan tâm** trên biểu đồ.

```python
def VolumeProfile(close: pandas.Series, volume: pandas.Series, high: pandas.Series = None, low: pandas.Series = None, bins: int = 20, use_typical: bool = False)
```

**Tham số:**

| Tên tham số  | Mô tả                                                                   | Kiểu dữ liệu  | Giá trị mặc định |
| ------------ | ----------------------------------------------------------------------- | ------------- | ---------------- |
| close        | Cột giá đóng cửa dùng để xác định mức giá giao dịch.                    | pandas.Series |                  |
| volume       | Cột khối lượng giao dịch tương ứng với từng mức giá.                    | pandas.Series |                  |
| high         | Cột giá cao nhất (sử dụng khi dùng Typical Price).                      | pandas.Series |                  |
| low          | Cột giá thấp nhất (sử dụng khi dùng Typical Price).                     | pandas.Series |                  |
| bins         | Số lượng khoảng giá để chia biểu đồ Volume Profile.                     | int           | 20               |
| use\_typical | Nếu **True**, dùng giá Typical = (High + Low + Close)/3 thay cho Close. | bool          | False            |

Ví dụ:

```python
fi = client.FiinIndicator()
vp = VolumeProfile(close=data["close"], volume=data["volume"], high=data["high"], low=data["low"], bins=20, use_typical=True)
print(vp.sort_values("volume", ascending=False))
```

### **8.4.5.** Accumulation Distribution Line (Chaikin)

> **Accumulation/Distribution Line (A/D Line)**, hay còn gọi là **Đường Tích lũy/Phân phối**, là một chỉ báo kỹ thuật dựa trên khối lượng được phát triển bởi **Marc Chaikin**.
>
> Chỉ báo này đo lường dòng chảy tiền tệ (Money Flow) vào hay ra khỏi một tài sản bằng cách so sánh giá đóng cửa của một kỳ so với phạm vi giá của kỳ đó, sau đó nhân với khối lượng giao dịch. Nó dựa trên nguyên tắc: **khối lượng đi trước giá**.

```python
def adl(high: pandas.Series, low: pandas.Series, close: pandas.Series, volume: pandas.Series)
```

**Tham số:**<br>

| Tên tham số | Mô tả                                                      | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ---------------------------------------------------------- | ------------- | ---------------- |
| high        | Cột giá cao nhất của mỗi phiên.                            | pandas.Series |                  |
| low         | Cột giá thấp nhất của mỗi phiên.                           | pandas.Series |                  |
| close       | Cột giá đóng cửa, dùng để xác định vị trí giá trong phiên. | pandas.Series |                  |
| volume      | Cột khối lượng giao dịch trong mỗi phiên.                  | pandas.Series |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
df['adl'] = fi.adl(df["high"], df["low"], df["close"], df["volume"])
print(df)
```

### **8.4.6.** Price Volume Trend

> **Price Volume Trend (PVT)**, hay còn gọi là **Xu hướng Giá Khối lượng**, là một chỉ báo phân tích kỹ thuật dựa trên khối lượng. Nó được thiết kế để đo lường **áp lực mua và bán** bằng cách kết hợp cả **sự thay đổi giá** và **khối lượng giao dịch**.
>
> PVT là một chỉ báo tích lũy (cumulative), tương tự như On-Balance Volume (OBV), nhưng nó được xem là chính xác hơn OBV vì nó điều chỉnh khối lượng được cộng hoặc trừ vào tổng tích lũy dựa trên **phần trăm thay đổi của giá**.

```python
def pvt(close: pandas.Series, volume: pandas.Series)
```

**Tham số:**<br>

| Tên tham số | Mô tả                               | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ----------------------------------- | ------------- | ---------------- |
| close       | Cột giá đóng cửa của mỗi phiên.     | pandas.Series |                  |
| volume      | Cột khối lượng giao dịch tương ứng. | pandas.Series |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
df['pvt'] = fi.pvt(df["close"], df["volume"])
print(vp.sort_values("volume", ascending=False))
```

### **8.4.7.** Point of Control (POC)

> **Point of Control (PoC)**, hay còn gọi là Điểm Kiểm soát không phải là **một chỉ báo độc lập** mà là một **thành phần quan trọng trong chỉ báo Hồ sơ Khối lượng (Volume Profile)**. Chỉ báo này đề cập đến **mức giá phổ biến nhất**, nơi khối lượng giao dịch cao nhất diễn ra trong một khung thời gian cụ thể. Chỉ báo này được phát triển lần đầu tiên bởi Peter Steidlmayer, cựu nhà giao dịch hàng hóa và thành viên của Sàn Giao dịch Chicago (CBOT).

```python
def poc(close: pd.Series, volume: pd.Series, high: pd.Series = None, low: pd.Series = None, bins: int = 20, use_typical: bool = False) -> pd.DataFrame: ...
```

**Tham số:**

| Tên tham số  | Mô tả                                                                   | Kiểu dữ liệu  | Giá trị mặc định |
| ------------ | ----------------------------------------------------------------------- | ------------- | ---------------- |
| close        | Cột giá đóng cửa dùng để xác định mức giá giao dịch.                    | pandas.Series |                  |
| volume       | Cột khối lượng giao dịch tương ứng với từng mức giá.                    | pandas.Series |                  |
| high         | Cột giá cao nhất (sử dụng khi dùng Typical Price).                      | pandas.Series |                  |
| low          | Cột giá thấp nhất (sử dụng khi dùng Typical Price).                     | pandas.Series |                  |
| bins         | Số lượng khoảng giá để chia biểu đồ Volume Profile.                     | int           | 20               |
| use\_typical | Nếu **True**, dùng giá Typical = (High + Low + Close)/3 thay cho Close. | bool          | False            |

Ví dụ:

```python
fi = client.FiinIndicator()
data[["poc_lower_price", "poc_upper_price", "poc_volume"]] = fi.poc(data["close"], data["volume"], data["high"], data["low"], bins=20, use_typical=True)
print(data)
```

Dữ liệu trả ra gồm 3 cột:

* poc\_lower\_price và poc\_upper\_price mang ý nghĩa là 2 đầu của khoảng giá được giao dịch nhiều nhất (VD: Tính từ ngày 2025-07-01 đến 2025-11-19, khoảng giá có khối lượng giao dịch nhiều nhất của mã MWG là từ 69113.075 đến 70218.87, tương tứng poc\_lower\_price = 69113.075 và poc\_upper\_price = 70218.87)
* poc\_volume: Khối lượng giao dịch của khoảng giá được giao dịch nhiều nhất tương ứng

Lưu ý:

* Các tham số close, volume, high, low là những pandas.Series phải đảm bảo có độ dài bằng nhau, tính tuần tự về thời gian là như nhau.
* Các tham số close, volume, high, low là những pandas.Series cũng cần đẩm bảo có tính tuần tự tăng dần theo chiều từ trên xuống dưới để đảm bảo số liệu trả ra được đúng đắn và có ý nghĩa.
* Các trường "poc\_lower\_price", "poc\_upper\_price", "poc\_volume" được trả ra cho mỗi dòng tương ứng với số liệu được tính rolling cho khoảng thời gian từ dòng đầu đến dòng được tính, vì vậy mặc định với  tham số bins truyền vào là bao nhiêu thì bấy nhiêu dòng đầu của các pandas.Series truyền vào sẽ không có dữ liệu vì phải đảm bảo có đủ số bins dữ liệu mới chia ra được từng đấy khoảng giá. Do vậy nếu bạn muốn tính được đầy đủ số liệu kể trong khoảng thời gian mong muốn cần truyền vào thừa ra để đảm bảo có đầy đủ số liệu.


# 8.5. Smart Money Concepts

### 8.**5.1. Fair Value Gap (FVG)**

Là một vùng giá chưa được lấp đầy trên biểu đồ, xuất hiện khi có sự mất cân bằng giữa cung và cầu. · Nếu cây nến hiện tại là nến tăng (bullish), fvg xuất hiện khi đỉnh của nến trước thấp hơn đáy của nến sau. Nếu cây nến hiện tại là nến giảm (bearish), fvg xuất hiện khi đáy của nến trước cao hơn đỉnh của nến sau.

```python
def fvg(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, join_consecutive: bool = True) -> pd.Series: ...
    
def fvg_top(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, join_consecutive: bool = True) -> pd.Series: ...
    
def fvg_bottom(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, join_consecutive: bool = True) -> pd.Series: ...
    
def fvg_mitigatedIndex(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, join_consecutive: bool = True) -> pd.Series: ...
```

**Tham số**

| Tên tham số       | Mô tả                                                                                                                         | Kiểu dữ liệu  | Giá trị mặc định |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------- | ---------------- |
| open              | Cột chứa giá mở cửa.                                                                                                          | pandas.Series |                  |
| high              | Cột chứa giá cao nhất.                                                                                                        | pandas.Series |                  |
| low               | Cột chứa giá thấp nhất.                                                                                                       | pandas.Series |                  |
| close             | Cột chứa giá đóng cửa.                                                                                                        | pandas.Series |                  |
| join\_consecutive | Nếu có nhiều khoảng (FVG) liên tiếp, chúng sẽ được gộp lại thành một, sử dụng mức cao nhất làm đỉnh và mức thấp nhất làm đáy. | bool          | True             |

Ví dụ:

```python
fi = client.FiinIndicator()
df['fvg'] = fi.fvg(df['open'],df['high'], df['low'], df['close'],join_consecutive=True)
print(df)
```

### **8.5.2. Swing Highs and Lows**

Đỉnh xoay (Swing High) xảy ra khi giá cao nhất của cây nến hiện tại là mức cao nhất trong một khoảng thời gian xác định trước và sau nó.

Đáy xoay (Swing Low) xảy ra khi giá thấp nhất của cây nến hiện tại là mức thấp nhất trong cùng khoảng thời gian đó.

```python
def swing_HL(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, swing_length: int = 50) -> pd.Series: ...
    
def swing_level(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, swing_length: int = 50)) -> pd.Series: ...
```

**Tham số**

| Tên tham số   | Mô tả                                                                | Kiểu dữ liệu  |    |
| ------------- | -------------------------------------------------------------------- | ------------- | -- |
| open          | Cột chứa giá mở cửa.                                                 | pandas.Series |    |
| high          | Cột chứa giá cao nhất.                                               | pandas.Series |    |
| low           | Cột chứa giá thấp nhất.                                              | pandas.Series |    |
| close         | Cột chứa giá đóng cửa.                                               | pandas.Series |    |
| swing\_length | Số lượng nến cần xét về trước và sau để xác định đỉnh hoặc đáy xoay. | int           | 50 |

Ví dụ:

```python
fi = client.FiinIndicator()
df['swing_HL'] = fi.swing_HL(df['open'],df['high'], df['low'], df['close'], swing_length = 50)
print(df)
```

### **8.5.3. Break of Structure (BOS) & Change of Character (CHoCH)**

BOS (Break of Structure): Khi giá phá vỡ cấu trúc xu hướng trước đó (tăng hoặc giảm), thể hiện sự thay đổi trong động lực thị trường.

ChoCH (Change of Character): Chỉ báo quan trọng thể hiện sự đảo chiều của xu hướng. CHoCH xảy ra khi xu hướng giảm chuyển sang tăng hoặc ngược lại.

```python
def break_of_structure(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, close_break: bool = True, swing_length: int = 50) -> pd.Series: ...
    
def chage_of_charactor(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, close_break: bool = True, swing_length: int = 50) -> pd.Series: ...
    
def bos_choch_level(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, close_break: bool = True, swing_length: int = 50) -> pd.Series: ...
    
def broken_index(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, close_break: bool = True, swing_length: int = 50) -> pd.Series: ...
```

**Tham số**

| Tên tham số   | Mô tả                                                                                               | Kiểu dữ liệu  | Mặc định |
| ------------- | --------------------------------------------------------------------------------------------------- | ------------- | -------- |
| open          | Cột chứa giá mở cửa.                                                                                | pandas.Series |          |
| high          | Cột chứa giá cao nhất.                                                                              | pandas.Series |          |
| low           | Cột chứa giá thấp nhất.                                                                             | pandas.Series |          |
| close         | Cột chứa giá đóng cửa.                                                                              | pandas.Series |          |
| close\_break  | Nếu True, xác nhận dựa trên giá đóng cửa của nến.Nếu False, xác nhận dựa trên mức cao/thấp của nến. | bool          | True     |
| swing\_length | Số lượng nến cần xét về trước và sau để xác định đỉnh hoặc đáy xoay.                                | int           | 50       |

Ví dụ:

<pre class="language-python"><code class="lang-python">fi = client.FiinIndicator()
df['break_of_structure'] = fi.break_of_structure(df['open'],df['high'], df['low'],df['close'],swing_length=50)
<strong>df['chage_of_charactor'] = fi.chage_of_charactor(df['open'],df['high'], df['low'],df['close'])
</strong>print(df)
</code></pre>

### **8.5.4. Order Blocks**

Vùng giá mà các tổ chức lớn đã đặt lệnh giao dịch, tạo ra những cú đẩy mạnh về giá. Khi giá quay lại vùng OB, đây thường là điểm vào lệnh tiềm năng.

```python
def ob(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, close_mitigation: bool = False, swing_length: int = 50) -> pd.Series: ...
    
def ob_top(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, close_mitigation: bool = False, swing_length: int = 50) -> pd.Series: ...
    
def ob_bottom(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, close_mitigation: bool = False, swing_length: int = 50) -> pd.Series: ...
    
def ob_volume(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, close_mitigation: bool = False, swing_length: int = 50) -> pd.Series: ...
    
def ob_mitigated_index(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, close_mitigation: bool = False, swing_length: int = 50) -> pd.Series: ...
    
def ob_percetage(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, close_mitigation: bool = False, swing_length: int = 50) -> pd.Series: ...
```

**Tham số**

| Tên tham số       | Mô tả                                                                                               | Kiểu dữ liệu  | Mặc định |
| ----------------- | --------------------------------------------------------------------------------------------------- | ------------- | -------- |
| open              | Cột chứa giá mở cửa.                                                                                | pandas.Series |          |
| high              | Cột chứa giá cao nhất.                                                                              | pandas.Series |          |
| low               | Cột chứa giá thấp nhất.                                                                             | pandas.Series |          |
| close             | Cột chứa giá đóng cửa.                                                                              | pandas.Series |          |
| volume            | Cột chứa khối lượng giao dịch.                                                                      | pandas.Series |          |
| close\_mitigation | Nếu True, xác nhận dựa trên giá đóng cửa của nến.Nếu False, xác nhận dựa trên mức cao/thấp của nến. | bool          | False    |
| swing\_length     | Số lượng nến cần xét.                                                                               | int           | 50       |

Ví dụ:

```python
fi = client.Indicator()
df['ob'] = fi.ob(df['open'],df['high'], df['low'],df['close'],df['volume'], close_mitigation = False, swing_length = 40)
df['ob_volume'] = fi.ob_volume(df['open'],df['high'], df['low'],df['close'],df['volume'])
print(df)
```

### **8.5.5. Liquidity**

Thanh khoản (Liquidity) xuất hiện khi có nhiều mức cao (highs) hoặc nhiều mức thấp (lows) nằm trong một phạm vi nhỏ, cho thấy sự tích lũy lệnh trong khu vực đó.

```python
def liquidity(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, range_percent: float = 0.01, swing_length: int = 50) -> pd.Series: ...
    
def liquidity_level(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, range_percent: float = 0.01, swing_length: int = 50) -> pd.Series: ...
    
def liquidity_end(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, range_percent: float = 0.01, swing_length: int = 50) -> pd.Series: ...
    
def liquidity_swept(self, open: pd.Series, high: pd.Series, low: pd.Series, close: pd.Series, range_percent: float = 0.01, swing_length: int = 50) -> pd.Series: ...
```

**Tham số**

| Tên tham số    | Mô tả                                                                | Kiểu dữ liệu  | Mặc định |
| -------------- | -------------------------------------------------------------------- | ------------- | -------- |
| open           | Cột chứa giá mở cửa.                                                 | pandas.Series |          |
| high           | Cột chứa giá cao nhất.                                               | pandas.Series |          |
| low            | Cột chứa giá thấp nhất.                                              | pandas.Series |          |
| close          | Cột chứa giá đóng cửa.                                               | pandas.Series |          |
| range\_percent | Phần trăm phạm vi giá được sử dụng để xác định thanh khoản.          | float         | 0.01     |
| swing\_length  | Số lượng nến cần xét về trước và sau để xác định đỉnh hoặc đáy xoay. | int           | 50       |

Ví dụ:

```python
// Some codepy

fi = client.FiinIndicator()
df['liquidity'] = fi.liquidity(df['open'],df['high'], df['low'],df['close'])
print(df)
```


# 8.6. Risk Indicators (Chỉ báo rủi ro)

### 8.6.1. Ulcer Index

**Ulcer Index (UI)**, hay **Chỉ số Loét**, là một chỉ báo quản lý rủi ro được phát triển bởi Peter Martin vào năm 1987. Mục đích của nó là đo lường **mức độ và thời gian kéo dài của sự sụt giảm giá (drawdown)** từ mức đỉnh cao nhất trước đó, nhằm định lượng "nỗi đau tâm lý" mà nhà đầu tư phải chịu đựng khi giá giảm.

Không giống như độ lệch chuẩn (Standard Deviation) - vốn coi tất cả các biến động giá (cả tăng và giảm) là rủi ro như nhau, Ulcer Index **chỉ tập trung vào rủi ro giảm giá (downside risk)**.

```python
def ulcer_index(close: pandas.Series, window: int = 14, smoothing_length: int = 14, signal_length: int = 52)
```

**Tham số**

| Tên tham số       | Mô tả                                           | Kiểu dữ liệu  | Giá trị mặc định |
| ----------------- | ----------------------------------------------- | ------------- | ---------------- |
| close             | Cột chứa giá đóng cửa.                          | pandas.Series |                  |
| window            | Số phiên tính trung bình động cho drawdown (%). | int           | 14               |
| smoothing\_length | Số phiên làm mượt Ulcer Index (SMA).            | int           | 14               |
| signal\_length    | Số phiên tính đường tín hiệu (SMA của UI mượt). | int           | 52               |

Ví dụ:

```python
fi = client.FiinIndicator()
df_ui = fi.ulcer_index(df["close"], window=14, smoothing_length=14, signal_length=52)
print(df_ui)
```


# 8.7. Money Flow Indicators (Chỉ báo dòng tiền)

### 8.7.1. Multi Color Dragon Extended (MCDX)

Chỉ báo **MCDX (Multi Color Dragon Extended)** là một công cụ phân tích kỹ thuật giúp nhà đầu tư nhận diện **dòng tiền tạo lập** và **xu hướng đầu tư** trên thị trường chứng khoán. Chỉ báo này sử dụng các màu sắc khác nhau để phân biệt các nhóm nhà đầu tư: màu đỏ đại diện cho **nhà đầu tư lớn (Banker)**, màu xanh cho **nhà đầu tư nhỏ lẻ (Retailer)** và màu vàng cho **nhà đầu cơ (Hot Money)**. Nhà đầu tư có thể sử dụng MCDX để theo dõi dòng tiền và đưa ra quyết định mua bán cổ phiếu phù hợp.

```python
def mcdx_banker(close: pandas.Series, rsi_base_banker: int = 50, rsi_period_banker: int = 50, rsi_base_hot_money: int = 30, rsi_period_hot_money: int = 40, sensitivity_banker: float = 1.5, sensitivity_hot: float = 0.7, banker_ma: int = 10)
def mcdx_hot_money(close: pandas.Series, rsi_base_banker: int = 50, rsi_period_banker: int = 50, rsi_base_hot_money: int = 30, rsi_period_hot_money: int = 40, sensitivity_banker: float = 1.5, sensitivity_hot: float = 0.7, banker_ma: int = 10)
def mcdx_retail(close: pandas.Series, rsi_base_banker: int = 50, rsi_period_banker: int = 50, rsi_base_hot_money: int = 30, rsi_period_hot_money: int = 40, sensitivity_banker: float = 1.5, sensitivity_hot: float = 0.7, banker_ma: int = 10)
```

**Tham số**

| Tên tham số             | Mô tả                                                                                                                                                                               | Kiểu dữ liệu  | Giá trị mặc định |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ---------------- |
| close                   | Cột chứa giá đóng cửa.                                                                                                                                                              | pandas.Series |                  |
| rsi\_base\_banker       | Mức ngưỡng RSI nền (base) của dòng tiền Banker (smart money). Đại diện cho mức “trung hòa” mà trên đó được coi là dòng tiền lớn đang vào.                                           | int           | 50               |
| rsi\_period\_banker     | Chu kỳ RSI dùng để tính dòng tiền Banker. Chu kỳ dài → đo động lượng dài hạn → phản ánh tích lũy/phân phối dài.                                                                     | int           | 50               |
| rsi\_base\_hot\_money   | Ngưỡng RSI nền cho dòng tiền Hot money (đầu cơ ngắn hạn, lướt sóng). Thấp hơn rsi\_base\_banker vì hot money nhạy hơn, vào sớm, rút sớm.                                            | int           | 30               |
| rsi\_period\_hot\_money | Chu kỳ RSI cho dòng tiền Hot money (ngắn hơn banker). Mặc định = 40 → phản ứng nhanh hơn, phù hợp nhịp trading ngắn hạn.                                                            | int           | 40               |
| sensitivity\_banker     | Hệ số nhạy điều chỉnh độ mạnh của dòng tiền Banker. Càng lớn → đường Banker tăng nhanh khi RSI vượt ngưỡng → dễ thấy khi dòng tiền lớn thật sự vào (thường trong khoảng 1.2 – 1.8). | float         | 1.5              |
| sensitivity\_hot        | Hệ số nhạy cho dòng tiền Hot money. Vì dòng này biến động nhanh, nên hệ số < 1 để tránh nhiễu quá mức (thường từ 0.5 – 0.8).                                                        | float         | 0.7              |
| banker\_ma              | Độ dài trung bình động (Moving Average) để làm mượt đường Banker. Giúp loại bỏ nhiễu ngắn hạn, dễ nhìn xu hướng dòng tiền lớn.                                                      | int           | 10               |

Ví dụ:

```python
fi = client.FiinIndicator()
df["banker"] = fi.mcdx_banker(df["close"], rsi_base_banker=50, rsi_period_banker=50, rsi_base_hot_money=30, rsi_period_hot_money=40, sensitivity_banker=1.5, sensitivity_hot=0.7, banker_ma=10)
df["hotmoney"] = fi.mcdx_hot_money(df["close"], rsi_base_banker=50, rsi_period_banker=50, rsi_base_hot_money=30, rsi_period_hot_money=40, sensitivity_banker=1.5, sensitivity_hot=0.7, banker_ma=10)
df["retail"] = fi.mcdx_retail(df["close"], rsi_base_banker=50, rsi_period_banker=50, rsi_base_hot_money=30, rsi_period_hot_money=40, sensitivity_banker=1.5, sensitivity_hot=0.7, banker_ma=10)
print(df)
```

Biểu đồ trực quan:

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FKb7ulDdom1EhAplnDtrx%2FMCDX.png?alt=media&amp;token=eeed8c5e-7a6f-4e87-8915-11aff72b0fe6" alt=""><figcaption></figcaption></figure>

Source code:

```python
import pandas as pd
import matplotlib.pyplot as plt
import mplfinance as mpf

from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

df = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["MWG"],
    fields=["open","high","low","close"],
    adjusted=True,
    by="1d",
    from_date="2024-10-23",
    lasted=True
).get_data()

fi = client.FiinIndicator()
df["banker"] = fi.mcdx_banker(df["close"])
df["hotmoney"] = fi.mcdx_hot_money(df["close"])
df["retail"] = fi.mcdx_retail(df["close"])

df['timestamp'] = pd.to_datetime(df['timestamp'])
df.set_index('timestamp', inplace=True)

# --- Vẽ biểu đồ ---
fig = mpf.figure(style='yahoo', figsize=(12, 8))

# Biểu đồ nến (trên)
ax1 = fig.add_subplot(2, 1, 1)
mpf.plot(df, type='candle', ax=ax1)
ax1.set_title('Biểu đồ nến MWG')

# Biểu đồ MCDX (dưới)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)

# Dùng numeric index để khớp trục với mplfinance
x = range(len(df))

# Bar chart đè nhau
width = 0.5
ax2.bar(x, df['banker'] + df['hotmoney'] + df['retail'], width=width, color='green', label='Retail')
ax2.bar(x, df['banker'] + df['hotmoney'], width=width, color='gold', label='Hot Money')
ax2.bar(x, df['banker'], width=width, color='red', label='Banker')

ax2.set_title('MCDX - Dòng tiền thông minh')
ax2.legend()
ax2.grid(True, linestyle='--', alpha=0.3)

plt.tight_layout()
plt.show()
```

### 8.7.2. Chaikin Money Flow (CMF)

**Chaikin Money Flow (CMF)** là một chỉ báo kỹ thuật đo lường **mức độ dòng tiền chảy vào (buying pressure)** hoặc **chảy ra (selling pressure)** khỏi một cổ phiếu trong một khoảng thời gian nhất định.\
Chỉ báo này kết hợp **vị trí giá đóng cửa trong biên độ dao động giá của phiên** (High–Low range) và **khối lượng giao dịch**, từ đó đánh giá xem dòng tiền “thông minh” đang **tích lũy** hay **phân phối**.

```python
def cmf(high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, window: int = 20) -> pd.Series: ...
```

**Tham số**

| Tên tham số | Mô tả                              | Kiểu dữ liệu  | Giá trị mặc định |
| ----------- | ---------------------------------- | ------------- | ---------------- |
| high        | Cột giá cao nhất.                  | pandas.Series |                  |
| low         | Cột giá thấp nhất.                 | pandas.Series |                  |
| close       | Giá đóng cửa.                      | pandas.Series |                  |
| volume      | Khối lượng khớp lệnh.              | pandas.Series |                  |
| window      | Số phiên tính CMF (rolling window) | int           | 20               |

Ví dụ:

```python
fi = client.FiinIndicator()
df['cmf_20'] = fi.cmf(high=df['high'], low=df['low'], close=df['close'], volume=df['volume'], window=20)
print(df)
```


# 8.8. Price Level Indicators (Chỉ báo biến động giá)

### 8.8.1. Fibonacci Retracement

Fibonacci Retracement là một công cụ phân tích kỹ thuật dùng để xác định các vùng giá có khả năng trở thành:

* Hỗ trợ (Support) trong xu hướng tăng
* Kháng cự (Resistance) trong xu hướng giảm

Chỉ báo dựa trên tỷ lệ vàng Fibonacci: 23.6%, 38.2%, 50.0%, 61.8%, 78.6%.

```python
def fib_retracement_uptrend(high: pd.Series, low: pd.Series) -> dict: ...
def fib_retracement_downtrend(high: pd.Series, low: pd.Series) -> dict: ...
```

**Tham số**

| Tên tham số | Mô tả                       | Kiểu dữ liệu | Giá trị mặc định |
| ----------- | --------------------------- | ------------ | ---------------- |
| high        | Swing High (đỉnh gần nhất). | float        |                  |
| low         | Swing Low (đáy gần nhất).   | float        |                  |

Ví dụ:

```python
fi = client.FiinIndicator()
fib_uptrend = fi.fib_retracement_uptrend(data["high"], data["low"])
fib_downtrend = fi.fib_retracement_downtrend(data["high"], data["low"])
print(fib_uptrend)
print(fib_downtrend)
```

Dữ liệu trả ra là dictionary chứa các cặp key - value sau:

* SwingHigh: Mức giá tương ứng điểm cao nhất
* SwingLow: Mức giá tương ứng điểm thấp nhất
* Các mức giá dựa trên tỷ lệ vàng Fibonacci: 23.6%, 38.2%, 50.0%, 61.8%, 78.6% (dùng hàm fib\_retracement\_uptrend sẽ là mức giá trên, fib\_retracement\_downtrend sẽ là mức giá dưới):
  * 0.236: Mức giá tương ứng tỷ lệ 23.6%
  * 0.382: Mức giá tương ứng tỷ lệ 38.2%
  * 0.500: Mức giá tương ứng tỷ lệ 50.0%
  * 0.618: Mức giá tương ứng tỷ lệ 61.8%
  * 0.786: Mức giá tương ứng tỷ lệ 78.6%


# 9. Danh sách mô hình Pattern


# 9.1. Mô hình biểu đồ

### 9.1.1. **Mô hình vai đầu vai (**&#x48;ead and Shoulders **Pattern)**

> Mô hình vai đầu vai (Head and Shoulders) là một **mô hình đảo chiều xu hướng phổ biến trong phân tích kỹ thuật**, thường xuất hiện ở đỉnh một xu hướng tăng để báo hiệu khả năng đảo chiều thành xu hướng giảm. Nó bao gồm ba đỉnh, trong đó đỉnh ở giữa (đầu) cao nhất, hai đỉnh hai bên (vai) có chiều cao tương đương, và được nối với nhau bởi một đường gọi là đường viền cổ (neckline).

```python
def detect_head_shoulder(self, df: pd.DataFrame, window: int = 10,tolerance: float = 0.01) -> pd.Series: ...
```

**Tham số**

| Tên tham số | Ý nghĩa                                                                                                            | Kiểu dữ liệu     | Giá trị mặc định |
| ----------- | ------------------------------------------------------------------------------------------------------------------ | ---------------- | ---------------- |
| df          | Dataframe chứa các giá trị để xác định mô hình vai đầu vai (bắt buộc phải có các cột 'high', 'low', 'close')       | pandas.Dataframe |                  |
| window      | Độ rộng nến để xác định các đỉnh của mô hình (đinh hoặc đáy cao nhất, thấp nhất trong độ rộng window nến ở 2 bên). | int              | 10               |
| tolerance   | Giá trị % ít nhất mà điểm đầu phải cao hơn 2 vai                                                                   | float            | 0.01             |

Ví dụ:

```python
pa = client.Pattern()
df["head_shoulder"] = pa.detect_head_shoulder(df, window=10, tolerance=0.01)
print(df)
```

Kết quả trả ra:

Mội pandas.Series sẽ đánh dấu các giá trị "Entry", "Left\_Shoulder", "Left\_Neck", "Head", "Right\_Neck", "Right\_Shoulder" tại các vị trí index trong DataFrame tương ứng được xác định là các đỉnh, đấy thỏa mãn điều kiện để tạo thành mô hình. Ví dụ:

```python
username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

df = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["HPG"],
    fields=["high","low","close"],
    adjusted=True,
    by="1d",
    from_date="2024-01-01",
    to_date="2024-12-31"
).get_data()

pa = client.Pattern()
df["head_shoulder"] = pa.detect_head_shoulder(df)
print(df)
```

Sẽ trả ra dữ liệu xác định mô hình vai đầu vai từ ngày 24/05/2024 đến 10/07/2024, DataFrame kết quả trả ra như sau:

| ticker | timestamp        | high     | low       | close     | head\_shoulder  |
| ------ | ---------------- | -------- | --------- | --------- | --------------- |
| ...    | ...              | ...      | ...       | ...       | ...             |
| HPG    | 2024-04-23 00:00 | 21249.36 | 20794.83  | 20908.46  | Entry           |
| HPG    | 2024-04-24 00:00 | 21931.16 | 21022.1   | 21817.53  |                 |
| HPG    | 2024-04-25 00:00 | 21741.77 | 21438.75  | 21628.14  |                 |
| HPG    | 2024-04-26 00:00 | 21628.14 | 21249.36  | 21514.51  |                 |
| ...    | ...              | ...      | ...       | ...       | ...             |
| HPG    | 2024-05-23 00:00 | 24582.35 | 23832.38  | 24582.35  |                 |
| HPG    | 2024-05-24 00:00 | 24582.35 | 23749.05  | 24082.37  | Left\_Shoulder  |
| HPG    | 2024-05-27 00:00 | 24415.69 | 23874.045 | 24082.37  |                 |
| HPG    | 2024-05-28 00:00 | 24332.36 | 23999.04  | 24290.695 |                 |
| HPG    | 2024-05-29 00:00 | 24374.03 | 23832.38  | 23832.38  |                 |
| HPG    | 2024-05-30 00:00 | 23790.72 | 23332.4   | 23540.725 | Left\_Neck      |
| ...    | ...              | ...      | ...       | ...       | ...             |
| HPG    | 2024-06-17 00:00 | 24957.34 | 24165.7   | 24540.69  | Head            |
| ...    | ...              | ...      | ...       | ...       | ...             |
| HPG    | 2024-07-01 00:00 | 23749.05 | 23374.07  | 23624.06  | Right\_Neck     |
| ...    | ...              | ...      | ...       | ...       | ...             |
| HPG    | 2024-07-10 00:00 | 24582.35 | 24124.04  | 24124.04  | Right\_Shoulder |
| ...    | ...              | ...      | ...       | ...       | ...             |

Biểu đồ trực quan hóa:

```python
username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

df = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["HPG"],
    fields=["high","low","close"],
    adjusted=True,
    by="1d",
    from_date="2024-01-01",
    to_date="2024-12-31"
).get_data()

pa = client.Pattern()
df["head_shoulder"] = pa.detect_head_shoulder(df)

# Xác định các điểm đầu, vai gáy trong dataframe để vẽ biểu đố
df["head_shoulder_points"] = np.select(
    [
        df["head_shoulder"].isin(["Left_Shoulder","Head","Right_Shoulder"]),
        df["head_shoulder"].isin(["Entry","Left_Neck","Right_Neck"])
    ],
    [df["high"], df["low"]],
    default=np.nan
)

# Xác định đường neckline
idx_entry = df.index[df['head_shoulder'] == 'Entry'][0]
idx_shoulder1 = df.index[df['head_shoulder'] == 'Left_Shoulder'][0]
idx_neck1 = df.index[df['head_shoulder'] == 'Left_Neck'][0]
idx_neck2 = df.index[df['head_shoulder'] == 'Right_Neck'][0]
idx_head = df.index[df['head_shoulder'] == 'Head'][0]

# tọa độ (x, y)
x1, y1 = idx_entry, df.loc[idx_entry, 'low']
x2, y2 = idx_shoulder1, df.loc[idx_shoulder1, 'high']
x3, y3 = idx_neck1, df.loc[idx_neck1, 'low']
x4, y4 = idx_neck2, df.loc[idx_neck2, 'low']

# hệ số góc và hệ số chặn
a1 = (y2 - y1) / (x2 - x1)
b1 = y1 - a1 * x1

a2 = (y4 - y3) / (x4 - x3)
b2 = y3 - a2 * x3

# giao điểm (x, y)
x_intersect = round((b2 - b1) / (a1 - a2))
y_intersect = a1 * x_intersect + b1

# --- Tìm điểm close đầu tiên nằm dưới L2 kể từ Right_Neck trở đi ---
break_idx = None
value_break = None
for i in range(idx_neck2, len(df)):
    y_line = a2 * i + b2
    if df.loc[i, 'close'] < y_line:
        break_idx = i
        value_break = y_line
        break

break_gap = df.loc[idx_head, 'high'] - value_break
target_idx = len(df) - 1
for i in range(break_idx, len(df)):
    if df.loc[i, 'close'] < value_break - break_gap:
        target_idx = i
        break

df["neck_line"] = None
df.loc[x_intersect, "neck_line"] = y_intersect
df.loc[break_idx, "neck_line"] = value_break
df.loc[break_idx, "head_shoulder_points"] = value_break
df['neck_line'] = df['neck_line'].apply(lambda x: np.nan if x is None else x)

# Chuyển timestamp
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M')
df.set_index('timestamp', inplace=True)

# Làm mượt (nối) giá trị head_shoulder để vẽ liền
df['head_shoulder_line'] = df['head_shoulder_points'].interpolate(method='linear')
df['neck_line'] = df['neck_line'].interpolate(method='linear')

# Chặn đoạn sau điểm cuối cùng có dữ liệu thật
last_valid = df['head_shoulder_points'].last_valid_index()
# last_valid_neck_line = df['neck_line'].last_valid_index()
df.loc[df.index > last_valid, 'head_shoulder_line'] = None
df.loc[df.index > last_valid, 'neck_line'] = None

# Tạo plot line
add_lines = [
    mpf.make_addplot(df['head_shoulder_line'], color='blue', width=1.5),
    mpf.make_addplot(df["neck_line"], color='blue', width=1.5, linestyle='--')
]

# Vẽ biểu đồ nến + line
fig, axes = mpf.plot(
    df[['open','high','low','close']],
    type='candle',
    style='yahoo',
    addplot=add_lines,
    title='Mô hình Vai - Đầu - Vai (liên tục)',
    figsize=(12,6),
    returnfig=True
)

# Vẽ đường dọc từ điểm cuối xuống break gap đơn vị giá
ax = axes[0]
ax.plot(
    [break_idx, break_idx],  # x: cùng timestamp
    [value_break, value_break - break_gap],        # y: từ giá trị xuống thấp hơn 2
    color='blue', linestyle='--', linewidth=1.2
)

ax.plot(
    [break_idx, target_idx],
    [value_break - break_gap, value_break - break_gap],
    color='blue', linestyle='--', linewidth=1.2
)

plt.show()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F8znuZ56lhfeF7u571lQJ%2FFigure_1.png?alt=media&amp;token=2f73484c-4a88-4ed3-bfa6-15dc690975b5" alt=""><figcaption></figcaption></figure>

### 9.1.2. **Mô hình vai đầu vai ngược (Inverse** Head and Shoulders **Pattern)**

> Mô hình vai đầu vai ngược (Inverse Head and Shoulders) là một mô hình phân tích kỹ thuật dùng để **dự báo sự đảo chiều từ xu hướng giảm sang xu hướng tăng**. Mô hình này bao gồm ba đáy, trong đó đáy ở giữa (đầu) là đáy thấp nhất, và hai đáy hai bên (vai trái, vai phải) cao hơn. Khi giá phá vỡ "đường viền cổ" (nối hai đỉnh giữa hai đáy) và có khối lượng giao dịch tăng mạnh, mô hình được xác nhận, cho thấy xu hướng tăng có thể bắt đầu.

```python
def detect_inverse_head_shoulder(self, df: pd.DataFrame, window: int = 10, tolerance: float = 0.01) -> pd.Series: ...
```

**Tham số**

| Tên tham số | Ý nghĩa                                                                                                            | Kiểu dữ liệu     | Giá trị mặc định |
| ----------- | ------------------------------------------------------------------------------------------------------------------ | ---------------- | ---------------- |
| df          | Dataframe chứa các giá trị để xác định mô hình vai đầu vai (bắt buộc phải có các cột 'high', 'low', 'close')       | pandas.Dataframe |                  |
| window      | Độ rộng nến để xác định các đỉnh của mô hình (đinh hoặc đáy cao nhất, thấp nhất trong độ rộng window nến ở 2 bên). | int              | 10               |
| tolerance   | Giá trị % ít nhất mà điểm đầu phải cao hơn 2 vai                                                                   | float            | 0.01             |

Ví dụ:

```python
pa = client.Pattern()
df["head_shoulder"] = pa.detect_inverse_head_shoulder(df, window=10, tolerance=0.01)
print(df)
```


# 9.2. Mô hình nến

Đang phát triển ...


# 10. Bộ lọc cổ phiếu

Mô tả cách sử dụng thư viện sau khi người dùng đã đăng nhập. Chi tiết được nêu ra ở cuối chương này.

Hàm được sử dụng để lọc nhanh danh sách cổ phiếu dựa trên các điều kiện định nghĩa sẵn, thay vì phải tự xử lý và tính toán dữ liệu từ đầu.

Hàm này đặc biệt hữu ích cho:

* Phân tích đầu tư
* Xây dựng chiến lược screening
* Tạo danh sách cổ phiếu theo tiêu chí định lượng (quant screening)

Cú pháp sử dụng:

```python
from FiinQuantX import FiinSession

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

data = client.StockScreening().get(
    filter=filter,
    screenerDate="YYYY-MM-DD",
    exchanges=[...],
    sectors=[...]
)
print(data)
```

**Tham số:**

| Tên tham số  | Mô tả                                                                                                                                                                                                                                                                                                                     | Kiểu dữ liệu | Mặc định         | Bắt buộc |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ---------------- | -------- |
| filter       | Bộ lọc, là list các điều kiện, mỗi điều kiện là một dict. Chi tiết cách dùng sẽ mô tả ở dưới                                                                                                                                                                                                                              | list         |                  | Có       |
| screenerDate | Ngày sàng lọc (date string có dạng "%Y-%m-%d")                                                                                                                                                                                                                                                                            | str          | datetime.now()   | Không    |
| exchanges    | Danh sách các sàn cần lọc cổ phiếu                                                                                                                                                                                                                                                                                        | list         | Tất cả các sàn   | Không    |
| sectors      | Danh sách các ngành cần lọc cổ phiếu (Điền các mã ngành như BANKS\_L2, OIL\_AND\_GAS\_L2, REAL\_ESTATE\_L2, CHEMICALS\_L2. Chi tiết xem tại bảng tra cứu tên phân ngành truyền vào hàm và ICB Code ở mục [1.2. Danh sách mã theo ngành](/ham-va-cong-thuc/1.-danh-muc-and-thong-tin-co-ban/1.2.-danh-sach-ma-theo-nganh)) | list         | Tất cả các ngành | Không    |

Dữ liệu có các thuộc tính:

| Tên thuộc tính                                                                                                                   | Mô tả                                                                      | Kiểu dữ liệu |
| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ------------ |
| Mã CK                                                                                                                            | Các mã chứng khoán thỏa mãn điều kiện bộ lọc                               | str          |
| Tên công ty                                                                                                                      | Tên gọi doanh nghiệp đầy đủ của các mã chứng khoán tương ứng               | str          |
| Sàn                                                                                                                              | Sàn giao dịch mà các mã chứng khoán tương ứng niêm yết                     | str          |
| Ngành L2                                                                                                                         | Tên ngành cấp 2 của các doanh nghiệp tương ứng                             | str          |
| Các cột động tùy thuộc vào số bộ lọc và kiểu tiêu chí bộ lọc thuộc nhóm Chỉ số chính và Báo cáo tài chính sẽ có cơ chế khác nhau | Số liệu chỉ số tương ứng của từng mã chứng khoán thỏa mãn điều kiện bộ lọc | float        |

Code mẫu lọc ra các cổ phiếu thuộc sàn HOSE và thuộc các lĩnh vực Hóa chất cấp 2, Bất động sản cấp 2 có tỷ lệ % freefloat trong khoảng từ 0.1 đến 0.5 và số cổ phiếu niêm yết trong khoảng từ 10 đến 200 triệu.

```python
filter = [
    {
        "indicatorName": "% Free Float",
        "conditionValues": [0.1, 0.5]
    },
    {
        "indicatorName": "Số cổ phiếu niêm yết",
        "conditionValues": [10000000, 200000000]
    }
]

data = client.StockScreening().get(
    filter=filter,
    screenerDate="2026-03-17",
    exchanges=["HOSE"],
    sectors=["CHEMICALS_L2","REAL_ESTATE_L2"]
)
print(data)
```

Kết quả trả ra là 1 dataframe dạng bảng như sau:

| Mã CK | Tên công ty       | Sàn  | Ngành L2     | % Free Float 2026-03-17 | Số cổ phiếu niêm yết 2026-03-17 |
| ----- | ----------------- | ---- | ------------ | ----------------------- | ------------------------------- |
| PHR   | Cao su Phước Hòa  | HOSE | Hóa chất     | 0.3500                  | 135499200.0                     |
| SZC   | Sonadezi Châu Đức | HOSE | Bất động sản | 0.4000                  | 179985860.0                     |
| ...   | ...               | ...  | ...          | ...                     | ...                             |
| BRC   | Cao su Bến Thành  | HOSE | Hóa chất     | 0.1300                  | 12375000.0                      |

Code mẫu lọc ra các cổ phiếu thuộc sàn HOSE và thuộc các lĩnh vực Hóa chất cấp 2, Bất động sản cấp 2 có Doanh thu thuần bán hàng và cung cấp dịch vụ trong cả năm 2025 lớn hơn giá trị doanh thu cao nhất trong 3 năm gần nhất liên tục và Doanh thu thuần bán hàng và cung cấp dịch vụ của riêng quý 4 năm 2025 đạt trên 10.000 tỷ.

```python
filter = [
    {
        "indicatorName":"3. Doanh thu thuần bán hàng và cung cấp dịch vụ",
        "interimCode":"Yearly",
        "indicatorInterimId": "2025",
        "conditionValues":[None,None],
        "additionalCondition": {
            "interimCode": "3_Recent_Continuous_Year",
            "operator": ">",
            "function": "Max"
        }
    },
    {
        "indicatorName":"3. Doanh thu thuần bán hàng và cung cấp dịch vụ",
        "interimCode":"Quarterly",
        "indicatorInterimId": "Q4-2025",
        "conditionValues":[10000000000000,None]
    }
]

data = client.StockScreening().get(
    filter=filter,
    screenerDate="2026-03-17",
    exchanges=["HOSE"],
    sectors=["CHEMICALS_L2","REAL_ESTATE_L2"]
)
print(data)
```

Kết quả trả ra là 1 dataframe dạng bảng như sau:

| Mã CK | Tên công ty | Sàn  | Ngành L2     | 3. Doanh thu thuần bán hàng và cung cấp dịch vụ 2025 | 3. Doanh thu thuần bán hàng và cung cấp dịch vụ 3 năm liên tiếp trước kỳ sàng lọc Lớn nhất của 2025 | 3. Doanh thu thuần bán hàng và cung cấp dịch vụ Q4-2025 |
| ----- | ----------- | ---- | ------------ | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| VIC   | VinGroup    | HOSE | Bất động sản | 3.3277E+14                                           | 1.89068E+14                                                                                         | 1.63159E+14                                             |
| VHM   | Vinhomes    | HOSE | Bất động sản | 1.54102E+14                                          | 1.03557E+14                                                                                         | 1.0301E+14                                              |


# 11. Dữ liệu hỗ trợ


# 11.1. Danh sách các cổ phiếu theo nhóm chỉ số

### Danh sách VN30

\['ACB', 'BCM', 'BID', 'BVH', 'CTG', 'FPT', 'GAS', 'GVR', 'HDB', 'HPG', 'LPB', 'MBB', 'MSN', 'MWG', 'PLX', 'SAB', 'SHB', 'SSB', 'SSI', 'STB', 'TCB', 'TPB', 'VCB', 'VHM', 'VIB', 'VIC', 'VJC', 'VNM', 'VPB', 'VRE']

### Danh sách VNINDEX

\['AAA', 'AAM', 'AAT', 'ABR', 'ABS', 'ABT', 'ACB', 'ACC', 'ACG', 'ACL', 'ADG', 'ADP', 'ADS', 'AGG', 'AGM', 'AGR', 'ANV', 'APG', 'APH', 'ASG', 'ASM', 'ASP', 'AST', 'ATP', 'BAF', 'BBC', 'BCE', 'BCG', 'BCM', 'BFC', 'BHN', 'BIC', 'BID', 'BKG', 'BMC', 'BMI', 'BMP', 'BRC', 'BSI', 'BSR', 'BTP', 'BTT', 'BVH', 'BWE', 'C32', 'C47', 'CCI', 'CCL', 'CDC', 'CHP', 'CIG', 'CII', 'CKG', 'CLC', 'CLL', 'CLW', 'CMG', 'CMV', 'CMX', 'CNG', 'COM', 'CRC', 'CRE', 'CRV', 'CSM', 'CSV', 'CTD', 'CTF', 'CTG', 'CTI', 'CTR', 'CTS', 'CVT', 'D2D', 'DAH', 'DAT', 'DBC', 'DBD', 'DBT', 'DC4', 'DCL', 'DCM', 'DGC', 'DGW', 'DHA', 'DHC', 'DHG', 'DHM', 'DIG', 'DLG', 'DMC', 'DPG', 'DPM', 'DPR', 'DQC', 'DRC', 'DRH', 'DRL', 'DSC', 'DSE', 'DSN', 'DTA', 'DTL', 'DTT', 'DVP', 'DXG', 'DXS', 'DXV', 'E1VFVN30', 'EIB', 'ELC', 'EVE', 'EVF', 'EVG', 'FCM', 'FCN', 'FDC', 'FIR', 'FIT', 'FMC', 'FPT', 'FRT', 'FTS', 'FUCTVGF3', 'FUCTVGF4', 'FUCTVGF5', 'FUCVREIT', 'FUEABVND', 'FUEBFVND', 'FUEDCMID', 'FUEFCV50', 'FUEIP100', 'FUEKIV30', 'FUEKIVFS', 'FUEKIVND', 'FUEMAV30', 'FUEMAVND', 'FUESSV30', 'FUESSV50', 'FUESSVFL', 'FUETCC50', 'FUEVFVND', 'FUEVN100', 'GAS', 'GDT', 'GEE', 'GEG', 'GEX', 'GIL', 'GMD', 'GMH', 'GSP', 'GTA', 'GVR', 'HAG', 'HAH', 'HAP', 'HAR', 'HAS', 'HAX', 'HCD', 'HCM', 'HDB', 'HDC', 'HDG', 'HHP', 'HHS', 'HHV', 'HID', 'HII', 'HMC', 'HNA', 'HPG', 'HPX', 'HQC', 'HRC', 'HSG', 'HSL', 'HT1', 'HTG', 'HTI', 'HTL', 'HTN', 'HTV', 'HU1', 'HUB', 'HVH', 'HVN', 'HVX', 'ICT', 'IDI', 'IJC', 'ILB', 'IMP', 'ITC', 'ITD', 'JVC', 'KBC', 'KDC', 'KDH', 'KHG', 'KHP', 'KMR', 'KOS', 'KPF', 'KSB', 'L10', 'LAF', 'LBM', 'LCG', 'LDG', 'LEC', 'LGC', 'LGL', 'LHG', 'LIX', 'LM8', 'LPB', 'LSS', 'MBB', 'MCM', 'MCP', 'MDG', 'MHC', 'MIG', 'MSB', 'MSH', 'MSN', 'MWG', 'NAB', 'NAF', 'NAV', 'NBB', 'NCT', 'NHA', 'NHH', 'NHT', 'NKG', 'NLG', 'NNC', 'NO1', 'NSC', 'NT2', 'NTL', 'NVL', 'NVT', 'OCB', 'OGC', 'OPC', 'ORS', 'PAC', 'PAN', 'PC1', 'PDN', 'PDR', 'PET', 'PGC', 'PGD', 'PGI', 'PGV', 'PHC', 'PHR', 'PIT', 'PJT', 'PLP', 'PLX', 'PMG', 'PNC', 'PNJ', 'POW', 'PPC', 'PSH', 'PTB', 'PTC', 'PTL', 'PVD', 'PVP', 'PVT', 'QCG', 'QNP', 'RAL', 'RDP', 'REE', 'RYG', 'S4A', 'SAB', 'SAM', 'SAV', 'SBA', 'SBG', 'SBT', 'SBV', 'SC5', 'SCR', 'SCS', 'SFC', 'SFG', 'SFI', 'SGN', 'SGR', 'SGT', 'SHA', 'SHB', 'SHI', 'SHP', 'SIP', 'SJD', 'SJS', 'SKG', 'SMA', 'SMB', 'SMC', 'SPM', 'SRC', 'SRF', 'SSB', 'SSC', 'SSI', 'ST8', 'STB', 'STG', 'STK', 'SVC', 'SVD', 'SVI', 'SVT', 'SZC', 'SZL', 'TBC', 'TCB', 'TCD', 'TCH', 'TCI', 'TCL', 'TCM', 'TCO', 'TCR', 'TCT', 'TDC', 'TDG', 'TDH', 'TDM', 'TDP', 'TDW', 'TEG', 'THG', 'TIP', 'TIX', 'TLD', 'TLG', 'TLH', 'TMP', 'TMS', 'TMT', 'TN1', 'TNC', 'TNH', 'TNI', 'TNT', 'TPB', 'TPC', 'TRA', 'TRC', 'TSC', 'TTA', 'TTE', 'TTF', 'TV2', 'TVB', 'TVS', 'TVT', 'TYA', 'UIC', 'VAF', 'VCA', 'VCB', 'VCF', 'VCG', 'VCI', 'VDP', 'VDS', 'VFG', 'VGC', 'VHC', 'VHM', 'VIB', 'VIC', 'VID', 'VIP', 'VIX', 'VJC', 'VMD', 'VND', 'VNE', 'VNG', 'VNL', 'VNM', 'VNS', 'VOS', 'VPB', 'VPD', 'VPG', 'VPH', 'VPI', 'VPS', 'VRC', 'VRE', 'VSC', 'VSH', 'VSI', 'VTB', 'VTO', 'VTP', 'YBM', 'YEG']

### Danh sách VN100

\['AAA', 'ACB', 'ANV', 'BCG', 'BCM', 'BID', 'BMP', 'BSI', 'BVH', 'BWE', 'CII', 'CMG', 'CTD', 'CTG', 'CTR', 'CTS', 'DBC', 'DCM', 'DGC', 'DGW', 'DIG', 'DPM', 'DSE', 'DXG', 'DXS', 'EIB', 'EVF', 'FPT', 'FRT', 'FTS', 'GAS', 'GEX', 'GMD', 'GVR', 'HAG', 'HCM', 'HDB', 'HDC', 'HDG', 'HHV', 'HPG', 'HSG', 'HT1', 'IMP', 'KBC', 'KDC', 'KDH', 'KOS', 'LPB', 'MBB', 'MSB', 'MSN', 'MWG', 'NAB', 'NKG', 'NLG', 'NT2', 'OCB', 'PAN', 'PC1', 'PDR', 'PHR', 'PLX', 'PNJ', 'POW', 'PPC', 'PTB', 'PVD', 'PVT', 'REE', 'SAB', 'SBT', 'SCS', 'SHB', 'SIP', 'SJS', 'SSB', 'SSI', 'STB', 'SZC', 'TCB', 'TCH', 'TLG', 'TPB', 'VCB', 'VCG', 'VCI', 'VGC', 'VHC', 'VHM', 'VIB', 'VIC', 'VIX', 'VJC', 'VND', 'VNM', 'VPB', 'VPI', 'VRE', 'VTP']

### Danh sách VNALL

\['AAA', 'AAM', 'ABR', 'ABS', 'ABT', 'ACB', 'ACC', 'ACL', 'ADS', 'AGG', 'AGR', 'ANV', 'APG', 'APH', 'ASM', 'ASP', 'AST', 'BAF', 'BCE', 'BCG', 'BCM', 'BFC', 'BIC', 'BID', 'BKG', 'BMC', 'BMI', 'BMP', 'BRC', 'BSI', 'BTP', 'BVH', 'BWE', 'C32', 'C47', 'CCL', 'CDC', 'CII', 'CLC', 'CLL', 'CMG', 'CMX', 'CNG', 'CRC', 'CRE', 'CSM', 'CSV', 'CTD', 'CTF', 'CTG', 'CTI', 'CTR', 'CTS', 'D2D', 'DAH', 'DBC', 'DBD', 'DBT', 'DC4', 'DCL', 'DCM', 'DGC', 'DGW', 'DHA', 'DHC', 'DHM', 'DIG', 'DPG', 'DPM', 'DPR', 'DQC', 'DRC', 'DRL', 'DSE', 'DSN', 'DTA', 'DVP', 'DXG', 'DXS', 'DXV', 'EIB', 'ELC', 'EVE', 'EVF', 'FCM', 'FCN', 'FIR', 'FIT', 'FMC', 'FPT', 'FRT', 'FTS', 'GAS', 'GDT', 'GEX', 'GIL', 'GMD', 'GMH', 'GSP', 'GTA', 'GVR', 'HAG', 'HAH', 'HAP', 'HAR', 'HAX', 'HCD', 'HCM', 'HDB', 'HDC', 'HDG', 'HHP', 'HHS', 'HHV', 'HID', 'HII', 'HMC', 'HPG', 'HPX', 'HQC', 'HSG', 'HSL', 'HT1', 'HTG', 'HTI', 'HTN', 'HTV', 'HUB', 'HVH', 'HVX', 'ICT', 'IDI', 'IJC', 'IMP', 'ITC', 'ITD', 'JVC', 'KBC', 'KDC', 'KDH', 'KHG', 'KHP', 'KMR', 'KOS', 'KSB', 'LAF', 'LBM', 'LCG', 'LDG', 'LHG', 'LIX', 'LPB', 'LSS', 'MBB', 'MCM', 'MCP', 'MHC', 'MIG', 'MSB', 'MSH', 'MSN', 'MWG', 'NAB', 'NAF', 'NBB', 'NCT', 'NHA', 'NHH', 'NKG', 'NLG', 'NNC', 'NO1', 'NSC', 'NT2', 'NTL', 'OCB', 'OGC', 'ORS', 'PAC', 'PAN', 'PC1', 'PDR', 'PET', 'PGC', 'PHC', 'PHR', 'PIT', 'PLP', 'PLX', 'PNJ', 'POW', 'PPC', 'PTB', 'PTC', 'PTL', 'PVD', 'PVP', 'PVT', 'QCG', 'RAL', 'REE', 'SAB', 'SAM', 'SAV', 'SBG', 'SBT', 'SCR', 'SCS', 'SFC', 'SFG', 'SFI', 'SGN', 'SGR', 'SGT', 'SHB', 'SHI', 'SIP', 'SJD', 'SJS', 'SKG', 'SMB', 'SSB', 'SSI', 'ST8', 'STB', 'STK', 'SVT', 'SZC', 'SZL', 'TCB', 'TCD', 'TCH', 'TCI', 'TCL', 'TCM', 'TCO', 'TCT', 'TDC', 'TDG', 'TDH', 'TDP', 'TEG', 'THG', 'TIP', 'TLD', 'TLG', 'TLH', 'TMT', 'TNH', 'TNI', 'TNT', 'TPB', 'TRC', 'TTA', 'TTF', 'TV2', 'TVS', 'TVT', 'TYA', 'UIC', 'VCA', 'VCB', 'VCG', 'VCI', 'VDS', 'VFG', 'VGC', 'VHC', 'VHM', 'VIB', 'VIC', 'VIP', 'VIX', 'VJC', 'VMD', 'VND', 'VNL', 'VNM', 'VNS', 'VOS', 'VPB', 'VPG', 'VPH', 'VPI', 'VRC', 'VRE', 'VSC', 'VTB', 'VTO', 'VTP', 'YEG']

### Danh sách VNXALL

\['AAA', 'AAM', 'AAT', 'AAV', 'ABR', 'ABS', 'ABT', 'ACB', 'ACC', 'ACG', 'ACL', 'ADG', 'ADP', 'ADS', 'AGG', 'AGM', 'AGR', 'ALT', 'AMC', 'AME', 'AMV', 'ANV', 'APG', 'APH', 'API', 'APS', 'ASG', 'ASM', 'ASP', 'AST', 'BAF', 'BAX', 'BBS', 'BCC', 'BCE', 'BCG', 'BFC', 'BIC', 'BKC', 'BKG', 'BMC', 'BMI', 'BMP', 'BNA', 'BPC', 'BRC', 'BSI', 'BST', 'BTP', 'BTS', 'BVH', 'BVS', 'BWE', 'C32', 'C47', 'C69', 'CAG', 'CAP', 'CCI', 'CCL', 'CDC', 'CEO', 'CET', 'CHP', 'CIA', 'CIG', 'CII', 'CKG', 'CLC', 'CLH', 'CLL', 'CMC', 'CMG', 'CMS', 'CMV', 'CMX', 'CNG', 'COM', 'CPC', 'CRC', 'CRE', 'CSC', 'CSM', 'CSV', 'CTC', 'CTD', 'CTF', 'CTG', 'CTI', 'CTP', 'CTR', 'CTS', 'CX8', 'D11', 'D2D', 'DAD', 'DAE', 'DAG', 'DAH', 'DAT', 'DBC', 'DBD', 'DBT', 'DC2', 'DC4', 'DCL', 'DCM', 'DDG', 'DGC', 'DGW', 'DHA', 'DHC', 'DHG', 'DHM', 'DHP', 'DHT', 'DIG', 'DIH', 'DL1', 'DLG', 'DMC', 'DNM', 'DNP', 'DP3', 'DPG', 'DPM', 'DPR', 'DQC', 'DRC', 'DRH', 'DRL', 'DS3', 'DSN', 'DST', 'DTA', 'DTC', 'DTD', 'DTG', 'DVG', 'DVM', 'DVP', 'DXG', 'DXP', 'DXS', 'DXV', 'EBS', 'ECI', 'EIB', 'EID', 'ELC', 'EMC', 'EVE', 'EVF', 'EVG', 'EVS', 'FCM', 'FCN', 'FDC', 'FID', 'FIR', 'FIT', 'FMC', 'FPT', 'FRT', 'FTS', 'GDT', 'GEG', 'GEX', 'GIC', 'GIL', 'GKM', 'GLT', 'GMA', 'GMC', 'GMD', 'GMH', 'GMX', 'GSP', 'GTA', 'HAD', 'HAG', 'HAH', 'HAP', 'HAR', 'HAS', 'HAT', 'HAX', 'HBS', 'HCC', 'HCD', 'HCM', 'HDA', 'HDB', 'HDC', 'HDG', 'HHP', 'HHS', 'HHV', 'HID', 'HII', 'HJS', 'HKT', 'HLC', 'HLD', 'HMC', 'HMH', 'HMR', 'HNA', 'HOM', 'HPG', 'HPX', 'HQC', 'HSG', 'HSL', 'HT1', 'HTG', 'HTI', 'HTL', 'HTN', 'HTP', 'HTV', 'HU1', 'HUB', 'HUT', 'HVH', 'HVT', 'HVX', 'IBC', 'ICG', 'ICT', 'IDC', 'IDI', 'IDJ', 'IDV', 'IJC', 'ILB', 'IMP', 'INC', 'INN', 'IPA', 'ITC', 'ITD', 'ITQ', 'IVS', 'JVC', 'KBC', 'KDC', 'KDH', 'KDM', 'KHG', 'KHP', 'KKC', 'KMR', 'KMT', 'KOS', 'KPF', 'KSB', 'KSD', 'KSF', 'KSQ', 'KST', 'KTS', 'L14', 'L18', 'L40', 'L61', 'L62', 'LAF', 'LAS', 'LBE', 'LBM', 'LCG', 'LDG', 'LDP', 'LGL', 'LHC', 'LHG', 'LIG', 'LIX', 'LM8', 'LPB', 'LSS', 'MAC', 'MBB', 'MBG', 'MBS', 'MCF', 'MCO', 'MCP', 'MDC', 'MDG', 'MED', 'MEL', 'MHC', 'MHL', 'MIG', 'MKV', 'MSB', 'MSH', 'MSN', 'MST', 'MWG', 'NAB', 'NAF', 'NAG', 'NAV', 'NBB', 'NBC', 'NBP', 'NCT', 'NDN', 'NDX', 'NET', 'NFC', 'NHA', 'NHH', 'NHT', 'NKG', 'NLG', 'NNC', 'NO1', 'NRC', 'NSC', 'NSH', 'NST', 'NT2', 'NTL', 'NTP', 'NVB', 'NVL', 'NVT', 'OCB', 'OCH', 'OGC', 'ONE', 'OPC', 'ORS', 'PAC', 'PAN', 'PBP', 'PC1', 'PCE', 'PCG', 'PCH', 'PCT', 'PDB', 'PDR', 'PET', 'PGC', 'PGI', 'PGN', 'PGS', 'PGT', 'PHC', 'PHR', 'PIC', 'PIT', 'PJT', 'PLC', 'PLP', 'PLX', 'PMB', 'PMP', 'PMS', 'PNJ', 'POT', 'POW', 'PPC', 'PPE', 'PPP', 'PPS', 'PPT', 'PPY', 'PRC', 'PRE', 'PSD', 'PSE', 'PSH', 'PSI', 'PSW', 'PTB', 'PTC', 'PTI', 'PTL', 'PTS', 'PV2', 'PVB', 'PVC', 'PVD', 'PVG', 'PVI', 'PVP', 'PVS', 'PVT', 'QCG', 'QNP', 'QTC', 'RAL', 'RCL', 'RDP', 'REE', 'S55', 'S99', 'SAB', 'SAM', 'SAV', 'SBA', 'SBG', 'SBT', 'SBV', 'SC5', 'SCG', 'SCI', 'SCR', 'SCS', 'SD5', 'SD6', 'SD9', 'SDA', 'SDG', 'SED', 'SFC', 'SFG', 'SFI', 'SGC', 'SGD', 'SGN', 'SGR', 'SGT', 'SHA', 'SHB', 'SHE', 'SHI', 'SHP', 'SHS', 'SIC', 'SIP', 'SJD', 'SJE', 'SJF', 'SJS', 'SKG', 'SLS', 'SMA', 'SMB', 'SMC', 'SMN', 'SMT', 'SPC', 'SPM', 'SRC', 'SRF', 'SSB', 'SSI', 'ST8', 'STB', 'STC', 'STK', 'STP', 'SVC', 'SVD', 'SVN', 'SVT', 'SZB', 'SZC', 'SZL', 'TA9', 'TAR', 'TBC', 'TCB', 'TCD', 'TCH', 'TCI', 'TCL', 'TCM', 'TCO', 'TCR', 'TCT', 'TDC', 'TDG', 'TDH', 'TDM', 'TDN', 'TDP', 'TDT', 'TEG', 'TFC', 'THD', 'THG', 'THI', 'THS', 'THT', 'TIG', 'TIP', 'TIX', 'TJC', 'TKU', 'TLD', 'TLG', 'TLH', 'TMB', 'TMC', 'TMP', 'TMS', 'TMT', 'TMX', 'TN1', 'TNA', 'TNC', 'TNG', 'TNH', 'TNI', 'TNT', 'TOT', 'TPB', 'TPC', 'TPP', 'TRA', 'TRC', 'TSB', 'TSC', 'TTA', 'TTB', 'TTC', 'TTF', 'TTH', 'TTL', 'TTT', 'TV2', 'TV3', 'TV4', 'TVB', 'TVC', 'TVD', 'TVS', 'TVT', 'TXM', 'TYA', 'UIC', 'UNI', 'V12', 'V21', 'VAF', 'VBC', 'VC1', 'VC2', 'VC3', 'VC6', 'VC7', 'VC9', 'VCA', 'VCB', 'VCC', 'VCG', 'VCI', 'VCM', 'VCS', 'VDP', 'VDS', 'VE1', 'VE3', 'VE8', 'VFG', 'VFS', 'VGC', 'VGS', 'VHC', 'VHE', 'VHM', 'VIB', 'VIC', 'VID', 'VIG', 'VIP', 'VIT', 'VIX', 'VJC', 'VLA', 'VMC', 'VMD', 'VMS', 'VNC', 'VND', 'VNE', 'VNF', 'VNG', 'VNL', 'VNM', 'VNR', 'VNS', 'VOS', 'VPB', 'VPD', 'VPG', 'VPH', 'VPI', 'VPS', 'VRC', 'VRE', 'VSA', 'VSC', 'VSH', 'VSM', 'VTB', 'VTC', 'VTH', 'VTO', 'VTP', 'VTV', 'VTZ', 'WCS', 'WSS', 'X20', 'YBM', 'YEG']

### Danh sách VNX50

\['ACB', 'CTG', 'DCM', 'DGC', 'DIG', 'DPM', 'EIB', 'FPT', 'FRT', 'GEX', 'GMD', 'HCM', 'HDB', 'HPG', 'HSG', 'HUT', 'IDC', 'KBC', 'KDC', 'KDH', 'LPB', 'MBB', 'MSB', 'MSN', 'MWG', 'NLG', 'PDR', 'PNJ', 'POW', 'PVD', 'PVS', 'SHB', 'SHS', 'SSB', 'SSI', 'STB', 'TCB', 'TPB', 'VCB', 'VCG', 'VCI', 'VHM', 'VIB', 'VIC', 'VJC', 'VND', 'VNM', 'VPB', 'VPI', 'VRE']

### Danh sách VNFIN

\['ACB', 'AGR', 'APG', 'BIC', 'BID', 'BMI', 'BSI', 'BVH', 'CTG', 'CTS', 'DSE', 'EIB', 'EVF', 'FIT', 'FTS', 'HCM', 'HDB', 'LPB', 'MBB', 'MIG', 'MSB', 'NAB', 'OCB', 'OGC', 'ORS', 'SHB', 'SSB', 'SSI', 'STB', 'TCB', 'TCI', 'TPB', 'TVS', 'VCB', 'VCI', 'VDS', 'VIB', 'VIX', 'VND', 'VPB']

### Danh sách VNFINSELECT

\['ACB', 'AGR', 'APG', 'BIC', 'BID', 'BMI', 'BSI', 'BVH', 'CTG', 'CTS', 'EIB', 'EVF', 'FIT', 'FTS', 'HCM', 'HDB', 'LPB', 'MBB', 'MIG', 'MSB', 'OCB', 'OGC', 'ORS', 'SHB', 'SSB', 'SSI', 'STB', 'TCB', 'TPB', 'TVS', 'VCB', 'VCI', 'VDS', 'VIB', 'VIX', 'VND', 'VPB']

### Danh sách VNFINLEAD

\['ACB', 'BID', 'CTG', 'EIB', 'HCM', 'HDB', 'LPB', 'MBB', 'MSB', 'NAB', 'OCB', 'SHB', 'SSB', 'SSI', 'STB', 'TCB', 'TPB', 'VCB', 'VCI', 'VIB', 'VIX', 'VND', 'VPB']

### Danh sách VNSI

\['BCM', 'BID', 'BMP', 'BVH', 'CTD', 'CTG', 'DCM', 'FPT', 'GMD', 'HDB', 'IMP', 'MBB', 'MWG', 'PAN', 'PNJ', 'SBT', 'VCB', 'VIC', 'VNM', 'VPB']

### Danh sách VNDIAMOND

\['ACB', 'BMP', 'CTG', 'FPT', 'GMD', 'HDB', 'KDH', 'MBB', 'MSB', 'MWG', 'NLG', 'OCB', 'PNJ', 'REE', 'TCB', 'TPB', 'VIB', 'VPB', 'VRE']

### Danh sách UpcomIndex

\['A32', 'AAH', 'AAS', 'ABA', 'ABB', 'ABC', 'ABI', 'ABW', 'ACE', 'ACM', 'ACS', 'ACV', 'AFX', 'AG1', 'AGF', 'AGP', 'AGX', 'AIC', 'AIG', 'ALV', 'AMD', 'AMP', 'AMS', 'ANT', 'APC', 'APF', 'APL', 'APP', 'APT', 'ART', 'ASA', 'ATA', 'ATB', 'ATG', 'AVC', 'AVF', 'AVG', 'BAL', 'BBH', 'BBM', 'BBT', 'BCA', 'BCB', 'BCP', 'BCR', 'BCV', 'BDG', 'BDT', 'BDW', 'BEL', 'BGE', 'BGT', 'BGW', 'BHA', 'BHC', 'BHG', 'BHH', 'BHI', 'BHK', 'BHP', 'BIG', 'BII', 'BIO', 'BLF', 'BLI', 'BLN', 'BLT', 'BMD', 'BMF', 'BMG', 'BMJ', 'BMK', 'BMN', 'BMS', 'BMV', 'BNW', 'BOT', 'BQB', 'BRR', 'BRS', 'BSA', 'BSD', 'BSG', 'BSH', 'BSL', 'BSP', 'BSQ', 'BT1', 'BT6', 'BTB', 'BTD', 'BTG', 'BTH', 'BTN', 'BTU', 'BTV', 'BVB', 'BVG', 'BVL', 'BVN', 'BWA', 'BWS', 'C12', 'C21', 'C22', 'C4G', 'C92', 'CAD', 'CAF', 'CAT', 'CBI', 'CBS', 'CBV', 'CC1', 'CC4', 'CCA', 'CCC', 'CCD', 'CCM', 'CCP', 'CCS', 'CCT', 'CCV', 'CDG', 'CDH', 'CDO', 'CDP', 'CDR', 'CEG', 'CEN', 'CFM', 'CFV', 'CGV', 'CH5', 'CHC', 'CHS', 'CI5', 'CID', 'CIP', 'CK8', 'CKA', 'CKD', 'CLG', 'CLX', 'CMD', 'CMF', 'CMI', 'CMK', 'CMM', 'CMN', 'CMP', 'CMT', 'CMW', 'CNA', 'CNC', 'CNN', 'CNT', 'CPA', 'CPH', 'CPI', 'CQN', 'CQT', 'CSI', 'CT3', 'CT6', 'CTA', 'CTC', 'CTN', 'CTW', 'CTX', 'CYC', 'DAC', 'DAG', 'DAN', 'DAS', 'DBM', 'DC1', 'DCF', 'DCG', 'DCH', 'DCR', 'DCS', 'DCT', 'DDB', 'DDH', 'DDM', 'DDN', 'DDV', 'DFC', 'DFF', 'DGT', 'DHB', 'DHD', 'DHN', 'DHQ', 'DIC', 'DID', 'DKC', 'DKG', 'DKW', 'DLD', 'DLR', 'DLT', 'DM7', 'DMH', 'DMN', 'DMS', 'DNA', 'DND', 'DNE', 'DNH', 'DNL', 'DNM', 'DNN', 'DNT', 'DNW', 'DO3', 'DOC', 'DOP', 'DP1', 'DP2', 'DPC', 'DPH', 'DPP', 'DPS', 'DRG', 'DRI', 'DSD', 'DSG', 'DSP', 'DTB', 'DTE', 'DTH', 'DTI', 'DTP', 'DUS', 'DVC', 'DVG', 'DVN', 'DVW', 'DWC', 'DWS', 'DXL', 'DZM', 'E12', 'E29', 'ECO', 'EFI', 'EGL', 'EIC', 'EIN', 'EME', 'EMG', 'EMS', 'EPC', 'EPH', 'ESL', 'FBA', 'FBC', 'FCC', 'FCS', 'FGL', 'FHH', 'FHN', 'FHS', 'FIC', 'FLC', 'FOC', 'FOX', 'FRC', 'FRM', 'FSO', 'FT1', 'FTI', 'FTM', 'FVN', 'G20', 'G30', 'G36', 'GAB', 'GCB', 'GCF', 'GDA', 'GER', 'GGG', 'GH3', 'GHC', 'GLC', 'GLW', 'GMC', 'GND', 'GPC', 'GSM', 'GTD', 'GTS', 'GTT', 'GVT', 'H11', 'HAC', 'HAF', 'HAI', 'HAM', 'HAN', 'HAV', 'HBC', 'HBD', 'HBH', 'HC1', 'HC3', 'HCB', 'HCI', 'HCO', 'HD2', 'HD6', 'HD8', 'HDM', 'HDO', 'HDP', 'HDS', 'HDW', 'HEC', 'HEJ', 'HEP', 'HES', 'HFB', 'HFC', 'HFX', 'HGT', 'HHG', 'HHI', 'HHN', 'HIG', 'HIO', 'HJC', 'HKB', 'HLA', 'HLB', 'HLO', 'HLS', 'HLT', 'HLY', 'HMD', 'HMG', 'HMS', 'HNB', 'HNC', 'HND', 'HNF', 'HNG', 'HNI', 'HNM', 'HNP', 'HNR', 'HOT', 'HPB', 'HPD', 'HPH', 'HPI', 'HPM', 'HPP', 'HPT', 'HPW', 'HRB', 'HSA', 'HSI', 'HSM', 'HSP', 'HSV', 'HT9', 'HTE', 'HTM', 'HTP', 'HTS', 'HTT', 'HU3', 'HU4', 'HU6', 'HUG', 'HVA', 'HVG', 'HWI', 'HWS', 'IBC', 'IBD', 'ICC', 'ICF', 'ICI', 'ICL', 'ICN', 'IDP', 'IFS', 'IHK', 'ILA', 'ILC', 'ILS', 'IME', 'IN4', 'ING', 'IRC', 'ISG', 'ISH', 'IST', 'ITA', 'ITS', 'JOS', 'KAC', 'KCB', 'KCE', 'KGM', 'KHD', 'KHL', 'KHW', 'KIP', 'KLB', 'KLF', 'KNA', 'KSH', 'KSS', 'KTC', 'KTL', 'KTT', 'KVC', 'KWA', 'L12', 'L35', 'L43', 'L44', 'L45', 'L61', 'L62', 'L63', 'LAI', 'LAW', 'LCC', 'LCM', 'LCS', 'LDW', 'LG9', 'LGM', 'LIC', 'LKW', 'LLM', 'LM3', 'LM7', 'LMC', 'LMH', 'LMI', 'LNC', 'LO5', 'LPT', 'LQN', 'LSG', 'LTC', 'LTG', 'LTQ', 'LUT', 'M10', 'MA1', 'MBN', 'MBT', 'MCG', 'MCH', 'MDA', 'MDF', 'MEC', 'MEF', 'MES', 'MFS', 'MGC', 'MGG', 'MGR', 'MH3', 'MHL', 'MIE', 'MIM', 'MKP', 'MLC', 'MLS', 'MML', 'MNB', 'MND', 'MPC', 'MPT', 'MPY', 'MQB', 'MQN', 'MRF', 'MSR', 'MT9', 'MTA', 'MTB', 'MTC', 'MTG', 'MTH', 'MTL', 'MTN', 'MTP', 'MTS', 'MTV', 'MTX', 'MVC', 'MVN', 'MZG', 'NAC', 'NAS', 'NAU', 'NAW', 'NBE', 'NBT', 'NCG', 'NCS', 'ND2', 'NDC', 'NDF', 'NDP', 'NDT', 'NDW', 'NED', 'NEM', 'NGC', 'NHP', 'NHV', 'NJC', 'NLS', 'NNT', 'NOS', 'NQB', 'NQN', 'NQT', 'NS2', 'NSG', 'NSL', 'NSS', 'NTB', 'NTC', 'NTF', 'NTT', 'NTW', 'NUE', 'NVP', 'NWT', 'NXT', 'ODE', 'OIL', 'ONW', 'PAI', 'PAP', 'PAS', 'PAT', 'PBC', 'PBT', 'PCC', 'PCF', 'PCM', 'PDC', 'PDV', 'PEC', 'PEG', 'PEQ', 'PFL', 'PGB', 'PHH', 'PHP', 'PHS', 'PID', 'PIS', 'PIV', 'PJS', 'PLA', 'PLE', 'PLO', 'PMJ', 'PMT', 'PMW', 'PND', 'PNG', 'PNP', 'PNT', 'POB', 'POM', 'POS', 'POV', 'PPH', 'PPI', 'PQN', 'PRO', 'PRT', 'PSB', 'PSG', 'PSL', 'PSN', 'PSP', 'PTE', 'PTG', 'PTH', 'PTO', 'PTP', 'PTT', 'PTV', 'PVA', 'PVE', 'PVH', 'PVL', 'PVM', 'PVO', 'PVR', 'PVV', 'PVX', 'PVY', 'PWA', 'PWS', 'PX1', 'PXA', 'PXC', 'PXI', 'PXL', 'PXM', 'PXS', 'PXT', 'QBS', 'QCC', 'QHW', 'QNC', 'QNS', 'QNT', 'QNU', 'QNW', 'QPH', 'QSP', 'QTP', 'RAT', 'RBC', 'RCC', 'RCD', 'REN', 'RGG', 'RIC', 'ROS', 'RTB', 'S12', 'S27', 'S72', 'S74', 'S96', 'SAC', 'SAL', 'SAP', 'SAS', 'SB1', 'SBB', 'SBC', 'SBD', 'SBH', 'SBL', 'SBM', 'SBR', 'SBS', 'SCC', 'SCD', 'SCJ', 'SCL', 'SCO', 'SCY', 'SD1', 'SD2', 'SD3', 'SD4', 'SD6', 'SD7', 'SD8', 'SDB', 'SDD', 'SDJ', 'SDK', 'SDP', 'SDT', 'SDV', 'SDX', 'SDY', 'SEA', 'SEP', 'SGB', 'SGI', 'SGP', 'SGS', 'SGV', 'SHC', 'SHG', 'SID', 'SIG', 'SII', 'SIV', 'SJC', 'SJF', 'SJG', 'SJM', 'SKH', 'SKN', 'SKV', 'SNC', 'SNZ', 'SP2', 'SPB', 'SPD', 'SPH', 'SPV', 'SQC', 'SRB', 'SSF', 'SSG', 'SSH', 'SSN', 'SST', 'STD', 'STH', 'STL', 'STS', 'STT', 'STW', 'SVG', 'SVH', 'SWC', 'SZE', 'SZG', 'TA6', 'TAB', 'TAL', 'TAN', 'TAR', 'TAW', 'TB8', 'TBD', 'TBH', 'TBR', 'TBT', 'TBW', 'TCJ', 'TCK', 'TCP', 'TCW', 'TDB', 'TDF', 'TDS', 'TED', 'TEL', 'TGG', 'TGP', 'TH1', 'THM', 'THN', 'THO', 'THP', 'THU', 'THW', 'TID', 'TIE', 'TIN', 'TIS', 'TKA', 'TKC', 'TKD', 'TKG', 'TL4', 'TLI', 'TLL', 'TLP', 'TLT', 'TMG', 'TMW', 'TNA', 'TNB', 'TNM', 'TNP', 'TNS', 'TNV', 'TNW', 'TOP', 'TOS', 'TOW', 'TPS', 'TQN', 'TQW', 'TR1', 'TRS', 'TRT', 'TS3', 'TS4', 'TSA', 'TSD', 'TSG', 'TSJ', 'TST', 'TT6', 'TTB', 'TTD', 'TTG', 'TTN', 'TTS', 'TTZ', 'TUG', 'TV1', 'TV6', 'TVA', 'TVG', 'TVH', 'TVM', 'TVN', 'TW3', 'UCT', 'UDC', 'UDJ', 'UDL', 'UEM', 'UMC', 'UPC', 'UPH', 'USC', 'USD', 'UTT', 'UXC', 'V11', 'V15', 'V45', 'VAB', 'VAV', 'VBB', 'VBG', 'VBH', 'VC5', 'VCE', 'VCP', 'VCR', 'VCT', 'VCW', 'VCX', 'VDB', 'VDG', 'VDN', 'VDT', 'VE2', 'VE9', 'VEA', 'VEC', 'VEF', 'VES', 'VET', 'VFC', 'VFR', 'VGG', 'VGI', 'VGL', 'VGR', 'VGT', 'VGV', 'VHD', 'VHF', 'VHG', 'VHH', 'VIE', 'VIH', 'VIM', 'VIN', 'VIR', 'VIW', 'VKC', 'VKP', 'VLB', 'VLC', 'VLF', 'VLG', 'VLP', 'VLW', 'VMA', 'VMG', 'VMK', 'VMT', 'VNA', 'VNB', 'VNH', 'VNI', 'VNP', 'VNX', 'VNY', 'VNZ', 'VOC', 'VPA', 'VPC', 'VPL', 'VPR', 'VPW', 'VQC', 'VRG', 'VSE', 'VSF', 'VSG', 'VSN', 'VST', 'VTA', 'VTD', 'VTE', 'VTG', 'VTI', 'VTK', 'VTL', 'VTM', 'VTQ', 'VTR', 'VTS', 'VTX', 'VUA', 'VUG', 'VVN', 'VVS', 'VW1', 'VW3', 'VWS', 'VXB', 'VXP', 'VXT', 'WSB', 'WTC', 'X26', 'X77', 'XDH', 'XHC', 'XLV', 'XMC', 'XMD', 'XMP', 'XPH', 'YBC', 'YTC']

### Danh sách VNMID

\['AAA', 'ANV', 'BCG', 'BMP', 'BSI', 'BWE', 'CII', 'CMG', 'CTD', 'CTR', 'CTS', 'DBC', 'DCM', 'DGC', 'DGW', 'DIG', 'DPM', 'DSE', 'DXG', 'DXS', 'EIB', 'EVF', 'FRT', 'FTS', 'GEX', 'GMD', 'HAG', 'HCM', 'HDC', 'HDG', 'HHV', 'HSG', 'HT1', 'IMP', 'KBC', 'KDC', 'KDH', 'KOS', 'MSB', 'NAB', 'NKG', 'NLG', 'NT2', 'OCB', 'PAN', 'PC1', 'PDR', 'PHR', 'PNJ', 'POW', 'PPC', 'PTB', 'PVD', 'PVT', 'REE', 'SBT', 'SCS', 'SIP', 'SJS', 'SZC', 'TCH', 'TLG', 'VCG', 'VCI', 'VGC', 'VHC', 'VIX', 'VND', 'VPI', 'VTP']

### Danh sách VNREAL

\['AGG', 'ASM', 'BCM', 'CCL', 'CRE', 'D2D', 'DTA', 'DXG', 'DXS', 'FIR', 'HAR', 'HDC', 'HPX', 'HQC', 'HTN', 'ITC', 'KBC', 'KDH', 'KHG', 'KOS', 'LDG', 'LHG', 'NBB', 'NLG', 'NTL', 'PDR', 'PTL', 'QCG', 'SCR', 'SGR', 'SIP', 'SJS', 'SZL', 'TDC', 'TDH', 'TEG', 'VHM', 'VIC', 'VPH', 'VPI', 'VRE']

### Danh sách VNMAT

\['AAA', 'ACC', 'APH', 'BFC', 'BMC', 'CRC', 'CSV', 'CTI', 'DCM', 'DGC', 'DHA', 'DHC', 'DHM', 'DPM', 'DPR', 'DXV', 'FCM', 'GMH', 'GVR', 'HAP', 'HHP', 'HII', 'HMC', 'HPG', 'HSG', 'HT1', 'HVX', 'KSB', 'LBM', 'MCP', 'NHH', 'NKG', 'NNC', 'PHR', 'PLP', 'SFG', 'TDP', 'THG', 'TLD', 'TLH', 'TNT', 'TRC', 'VCA', 'VFG']

### Danh sách VNCONS

\['AAM', 'ABT', 'ACL', 'ANV', 'BAF', 'CLC', 'CMX', 'DBC', 'FMC', 'HAG', 'HSL', 'IDI', 'KDC', 'LAF', 'LIX', 'LSS', 'MCM', 'MSN', 'NAF', 'NSC', 'PAN', 'SAB', 'SBT', 'SMB', 'VHC', 'VNM']

### Danh sách HNXIndex

\['AAV', 'ADC', 'ALT', 'AMC', 'AME', 'AMV', 'API', 'APS', 'ARM', 'ATS', 'BAB', 'BAX', 'BBS', 'BCC', 'BCF', 'BCH', 'BDB', 'BED', 'BKC', 'BNA', 'BPC', 'BSC', 'BST', 'BTS', 'BTW', 'BVS', 'BXH', 'C69', 'CAG', 'CAN', 'CAP', 'CAR', 'CCR', 'CDN', 'CEO', 'CET', 'CIA', 'CJC', 'CKV', 'CLH', 'CLM', 'CMC', 'CMS', 'CPC', 'CSC', 'CST', 'CTB', 'CTP', 'CTT', 'CVN', 'CX8', 'D11', 'DAD', 'DAE', 'DC2', 'DDG', 'DHP', 'DHT', 'DIH', 'DL1', 'DNC', 'DNP', 'DP3', 'DS3', 'DST', 'DTC', 'DTD', 'DTG', 'DTK', 'DVM', 'DXP', 'EBS', 'ECI', 'EID', 'EVS', 'FID', 'GDW', 'GIC', 'GKM', 'GLT', 'GMA', 'GMX', 'HAD', 'HAT', 'HBS', 'HCC', 'HCT', 'HDA', 'HEV', 'HGM', 'HHC', 'HJS', 'HKT', 'HLC', 'HLD', 'HMH', 'HMR', 'HOM', 'HTC', 'HUT', 'HVT', 'ICG', 'IDC', 'IDJ', 'IDV', 'INC', 'INN', 'IPA', 'ITQ', 'IVS', 'KDM', 'KHS', 'KKC', 'KMT', 'KSD', 'KSF', 'KSQ', 'KST', 'KSV', 'KTS', 'L14', 'L18', 'L40', 'LAS', 'LBE', 'LCD', 'LDP', 'LHC', 'LIG', 'MAC', 'MAS', 'MBG', 'MBS', 'MCC', 'MCF', 'MCO', 'MDC', 'MDD', 'MED', 'MEL', 'MIC', 'MKV', 'MST', 'MVB', 'NAG', 'NAP', 'NBC', 'NBP', 'NBW', 'NDN', 'NDX', 'NET', 'NFC', 'NHC', 'NRC', 'NSH', 'NST', 'NTH', 'NTP', 'NVB', 'OCH', 'ONE', 'PBP', 'PCE', 'PCG', 'PCH', 'PCT', 'PDB', 'PEN', 'PGN', 'PGS', 'PGT', 'PHN', 'PIA', 'PIC', 'PJC', 'PLC', 'PMB', 'PMC', 'PMP', 'PMS', 'POT', 'PPE', 'PPP', 'PPS', 'PPT', 'PPY', 'PRC', 'PRE', 'PSC', 'PSD', 'PSE', 'PSI', 'PSW', 'PTD', 'PTI', 'PTS', 'PTX', 'PV2', 'PVB', 'PVC', 'PVG', 'PVI', 'PVS', 'PXK', 'QHD', 'QST', 'QTC', 'RCL', 'S55', 'S99', 'SAF', 'SCG', 'SCI', 'SD5', 'SD9', 'SDA', 'SDC', 'SDG', 'SDN', 'SDU', 'SEB', 'SED', 'SFN', 'SGC', 'SGD', 'SGH', 'SHE', 'SHN', 'SHS', 'SJ1', 'SJE', 'SLS', 'SMN', 'SMT', 'SPC', 'SPI', 'SRA', 'SSM', 'STC', 'STP', 'SVN', 'SZB', 'TA9', 'TBX', 'TDT', 'TET', 'TFC', 'THB', 'THD', 'THS', 'THT', 'TIG', 'TJC', 'TKU', 'TMB', 'TMC', 'TMX', 'TNG', 'TOT', 'TPH', 'TPP', 'TSB', 'TTC', 'TTH', 'TTL', 'TTT', 'TV3', 'TV4', 'TVC', 'TVD', 'TXM', 'UNI', 'V12', 'V21', 'VBC', 'VC1', 'VC2', 'VC3', 'VC6', 'VC7', 'VC9', 'VCC', 'VCM', 'VCS', 'VDL', 'VE1', 'VE3', 'VE4', 'VE8', 'VFS', 'VGP', 'VGS', 'VHE', 'VHL', 'VIF', 'VIG', 'VIT', 'VLA', 'VMC', 'VMS', 'VNC', 'VNF', 'VNR', 'VNT', 'VSA', 'VSM', 'VTC', 'VTH', 'VTJ', 'VTV', 'VTZ', 'WCS', 'WSS', 'X20']

### Danh sách VNIND

\['ABR', 'ABS', 'BCE', 'BCG', 'BKG', 'BMP', 'BRC', 'C32', 'C47', 'CDC', 'CII', 'CLL', 'CTD', 'CTR', 'DC4', 'DIG', 'DPG', 'DQC', 'DVP', 'FCN', 'GEX', 'GMD', 'HAH', 'HCD', 'HDG', 'HHS', 'HHV', 'HID', 'HTI', 'HTV', 'HUB', 'HVH', 'IJC', 'ITD', 'LCG', 'MHC', 'NCT', 'NHA', 'NO1', 'PC1', 'PET', 'PHC', 'PIT', 'PTC', 'RAL', 'REE', 'SAM', 'SBG', 'SCS', 'SFI', 'SGN', 'SHI', 'SKG', 'ST8', 'SZC', 'TCD', 'TCH', 'TCL', 'TCO', 'TIP', 'TLG', 'TNI', 'TV2', 'TYA', 'VCG', 'VGC', 'VIP', 'VJC', 'VNL', 'VNS', 'VOS', 'VPG', 'VRC', 'VSC', 'VTO', 'VTP']

### Danh sách VNSML

\['AAM', 'ABR', 'ABS', 'ABT', 'ACC', 'ACL', 'ADS', 'AGG', 'AGR', 'APG', 'APH', 'ASM', 'ASP', 'AST', 'BAF', 'BCE', 'BFC', 'BIC', 'BKG', 'BMC', 'BMI', 'BRC', 'BTP', 'C32', 'C47', 'CCL', 'CDC', 'CLC', 'CLL', 'CMX', 'CNG', 'CRC', 'CRE', 'CSM', 'CSV', 'CTF', 'CTI', 'D2D', 'DAH', 'DBD', 'DBT', 'DC4', 'DCL', 'DHA', 'DHC', 'DHM', 'DPG', 'DPR', 'DQC', 'DRC', 'DRL', 'DSN', 'DTA', 'DVP', 'DXV', 'ELC', 'EVE', 'FCM', 'FCN', 'FIR', 'FIT', 'FMC', 'GDT', 'GIL', 'GMH', 'GSP', 'GTA', 'HAH', 'HAP', 'HAR', 'HAX', 'HCD', 'HHP', 'HHS', 'HID', 'HII', 'HMC', 'HPX', 'HQC', 'HSL', 'HTG', 'HTI', 'HTN', 'HTV', 'HUB', 'HVH', 'HVX', 'ICT', 'IDI', 'IJC', 'ITC', 'ITD', 'JVC', 'KHG', 'KHP', 'KMR', 'KSB', 'LAF', 'LBM', 'LCG', 'LDG', 'LHG', 'LIX', 'LSS', 'MCM', 'MCP', 'MHC', 'MIG', 'MSH', 'NAF', 'NBB', 'NCT', 'NHA', 'NHH', 'NNC', 'NO1', 'NSC', 'NTL', 'OGC', 'ORS', 'PAC', 'PET', 'PGC', 'PHC', 'PIT', 'PLP', 'PTC', 'PTL', 'PVP', 'QCG', 'RAL', 'SAM', 'SAV', 'SBG', 'SCR', 'SFC', 'SFG', 'SFI', 'SGN', 'SGR', 'SGT', 'SHI', 'SJD', 'SKG', 'SMB', 'ST8', 'STK', 'SVT', 'SZL', 'TCD', 'TCI', 'TCL', 'TCM', 'TCO', 'TCT', 'TDC', 'TDG', 'TDH', 'TDP', 'TEG', 'THG', 'TIP', 'TLD', 'TLH', 'TMT', 'TNH', 'TNI', 'TNT', 'TRC', 'TTA', 'TTF', 'TV2', 'TVS', 'TVT', 'TYA', 'UIC', 'VCA', 'VDS', 'VFG', 'VIP', 'VMD', 'VNL', 'VNS', 'VOS', 'VPG', 'VPH', 'VRC', 'VSC', 'VTB', 'VTO', 'YEG']

### Danh sách VNIT

\['CMG', 'DGW', 'ELC', 'FPT', 'ICT']

### Danh sách VNCOND

\['ADS', 'AST', 'CSM', 'CTF', 'DAH', 'DRC', 'DSN', 'EVE', 'FRT', 'GDT', 'GIL', 'GTA', 'HAX', 'HTG', 'KMR', 'MSH', 'MWG', 'PAC', 'PNJ', 'PTB', 'SAV', 'SFC', 'STK', 'SVT', 'TCM', 'TCT', 'TMT', 'TTF', 'TVT', 'VTB']

### Danh sách HNX30

\['CAP', 'CEO', 'DHT', 'DTD', 'DVM', 'DXP', 'HLD', 'HUT', 'IDC', 'IDV', 'L14', 'L18', 'LAS', 'LHC', 'MBS', 'NTP', 'NVB', 'PLC', 'PSD', 'PVB', 'PVC', 'PVS', 'SHS', 'SLS', 'TIG', 'TMB', 'TNG', 'TVD', 'VC3', 'VCS']

### Danh sách VNENE

\['ASP', 'CNG', 'GSP', 'PGC', 'PLX', 'PVD', 'PVP', 'PVT', 'TDG']

### Danh sách VNHEAL

\['DBD', 'DBT', 'DCL', 'IMP', 'JVC', 'TNH', 'VMD']


# 11.2. Danh sách nhóm ngành ICB

| ticker (dùng để điền vào biến của hàm)       | Tên ICB                                                        | Cấp độ ICB |
| -------------------------------------------- | -------------------------------------------------------------- | ---------: |
| Oil And Gas                                  | Dầu khí                                                        |          1 |
| Oil And Gas                                  | Dầu khí                                                        |          2 |
| Oil & Gas Producers                          | Sản xuất Dầu khí                                               |          3 |
| Exploration & Production                     | Sản xuất và Khai thác dầu khí                                  |          4 |
| Integrated Oil & Gas                         | Tổ hợp Dầu khí                                                 |          4 |
| Oil Equipment, Services & Distribution       | Thiết bị, Dịch vụ và Phân phối Dầu khí                         |          3 |
| Oil Equipment & Services                     | Thiết bị và Dịch vụ Dầu khí                                    |          4 |
| Pipelines                                    | Ống dẫn Dầu                                                    |          4 |
| Basic Materials                              | Nguyên vật liệu                                                |          1 |
| Chemicals                                    | Hóa chất                                                       |          2 |
| Chemicals                                    | Hóa chất                                                       |          3 |
| Commodity Chemicals                          | Nhựa, cao su & sợi                                             |          4 |
| Specialty Chemicals                          | Sản phẩm hóa dầu, Nông dược & Hóa chất khác                    |          4 |
| Basic Resources                              | Tài nguyên Cơ bản                                              |          2 |
| Forestry & Paper                             | Lâm nghiệp và Giấy                                             |          3 |
| Forestry                                     | Lâm sản và Chế biến gỗ                                         |          4 |
| Paper                                        | Sản xuất giấy                                                  |          4 |
| Industrial Metals & Mining                   | Kim loại                                                       |          3 |
| Aluminum                                     | Nhôm                                                           |          4 |
| Nonferrous Metals                            | Kim Loại màu                                                   |          4 |
| Steel                                        | Thép và sản phẩm thép                                          |          4 |
| Mining                                       | Khai khoáng                                                    |          3 |
| Coal                                         | Khai thác Than                                                 |          4 |
| Diamonds & Gemstones                         | Đá quý và Kim cương                                            |          4 |
| General Mining                               | Khai khoáng                                                    |          4 |
| Gold Mining                                  | Khai thác vàng                                                 |          4 |
| Platinum & Precious Metals                   | Bạch kim & Kim loại quý khác                                   |          4 |
| Industrials                                  | Công nghiệp                                                    |          1 |
| Construction & Materials                     | Xây dựng và Vật liệu                                           |          2 |
| Construction & Materials                     | Xây dựng và Vật liệu                                           |          3 |
| Building Materials & Fixtures                | Vật liệu xây dựng & Nội thất                                   |          4 |
| Heavy Construction                           | Xây dựng                                                       |          4 |
| Industrial Goods & Services                  | Hàng & Dịch vụ Công nghiệp                                     |          2 |
| Aerospace & Defense                          | Hàng không & Quốc phòng                                        |          3 |
| Aerospace                                    | Công nghiệp hàng không                                         |          4 |
| Defense                                      | Quốc phòng                                                     |          4 |
| General Industrials                          | Hàng công nghiệp                                               |          3 |
| Containers & Packaging                       | Containers & Đóng gói                                          |          4 |
| Diversified Industrials                      | Công nghiệp phức hợp                                           |          4 |
| Electronic & Electrical Equipment            | Điện tử & Thiết bị điện                                        |          3 |
| Electrical Components & Equipment            | Hàng điện & điện tử                                            |          4 |
| Electronic Equipment                         | Thiết bị điện                                                  |          4 |
| Industrial Engineering                       | Công nghiệp nặng                                               |          3 |
| Commercial Vehicles & Trucks                 | Xe tải & Đóng tàu                                              |          4 |
| Industrial Machinery                         | Máy công nghiệp                                                |          4 |
| Industrial Transportation                    | Vận tải                                                        |          3 |
| Delivery Services                            | Chuyển phát nhanh                                              |          4 |
| Marine Transportation                        | Vận tải Thủy                                                   |          4 |
| Railroads                                    | Đường sắt                                                      |          4 |
| Transportation Services                      | Kho bãi, hậu cần và bảo dưỡng                                  |          4 |
| Trucking                                     | Dịch vụ vận tải                                                |          4 |
| Support Services                             | Tư vấn & Hỗ trợ Kinh doanh                                     |          3 |
| Business Support Services                    | Tư vấn & Hỗ trợ KD                                             |          4 |
| Business Training & Employment Agencies      | Đào tạo & Việc làm                                             |          4 |
| Financial Administration                     | Quản lý Tài chính                                              |          4 |
| Industrial Suppliers                         | Nhà cung cấp thiết bị                                          |          4 |
| Waste & Disposal Services                    | Chất thải & Môi trường                                         |          4 |
| Consumer Goods                               | Hàng Tiêu dùng                                                 |          1 |
| Automobiles & Parts                          | Ô tô và phụ tùng                                               |          2 |
| Automobiles & Parts                          | Ô tô và phụ tùng                                               |          3 |
| Automobiles                                  | Sản xuất ô tô                                                  |          4 |
| Auto Parts                                   | Phụ tùng ô tô                                                  |          4 |
| Tires                                        | Lốp xe                                                         |          4 |
| Food & Beverage                              | Thực phẩm và đồ uống                                           |          2 |
| Beverages                                    | Bia và đồ uống                                                 |          3 |
| Brewers                                      | Sản xuất bia                                                   |          4 |
| Distillers & Vintners                        | Vang & Rượu mạnh                                               |          4 |
| Soft Drinks                                  | Đồ uống & giải khát                                            |          4 |
| Food Producers                               | Sản xuất thực phẩm                                             |          3 |
| Farming & Fishing                            | Nuôi trồng nông & hải sản                                      |          4 |
| Food Products                                | Thực phẩm                                                      |          4 |
| Personal & Household Goods                   | Hàng cá nhân & Gia dụng                                        |          2 |
| Household Goods & Home Construction          | Hàng gia dụng                                                  |          3 |
| Durable Household Products                   | Đồ gia dụng lâu bền                                            |          4 |
| Nondurable Household Products                | Đồ gia dụng một lần                                            |          4 |
| Furnishings                                  | Thiết bị gia dụng                                              |          4 |
| Home Construction                            | Xây nhà                                                        |          4 |
| Leisure Goods                                | Hàng hóa giải trí                                              |          3 |
| Consumer Electronics                         | Điện tử tiêu dùng                                              |          4 |
| Recreational Products                        | Sản phẩm nghệ thuật                                            |          4 |
| Toys                                         | Đồ chơi                                                        |          4 |
| Personal Goods                               | Hàng cá nhân                                                   |          3 |
| Clothing & Accessories                       | Hàng May mặc                                                   |          4 |
| Footwear                                     | Giầy dép                                                       |          4 |
| Personal Products                            | Hàng cá nhân                                                   |          4 |
| Tobacco                                      | Thuốc lá                                                       |          3 |
| Tobacco                                      | Thuốc lá                                                       |          4 |
| Health Care                                  | Dược phẩm và Y tế                                              |          1 |
| Health Care                                  | Y tế                                                           |          2 |
| Health Care Equipment & Services             | Thiết bị và Dịch vụ Y tế                                       |          3 |
| Health Care Providers                        | Chăm sóc y tế                                                  |          4 |
| Medical Equipment                            | Thiết bị y tế                                                  |          4 |
| Medical Supplies                             | Dụng cụ y tế                                                   |          4 |
| Pharmaceuticals & Biotechnology              | Dược phẩm                                                      |          3 |
| Biotechnology                                | Công nghệ sinh học                                             |          4 |
| Pharmaceuticals                              | Dược phẩm                                                      |          4 |
| Consumer Services                            | Dịch vụ Tiêu dùng                                              |          1 |
| Retail                                       | Bán lẻ                                                         |          2 |
| Food & Drug Retailers                        | Phân phối thực phẩm & dược phẩm                                |          3 |
| Drug Retailers                               | Phân phối dược phẩm                                            |          4 |
| Food Retailers & Wholesalers                 | Phân phối thực phẩm                                            |          4 |
| General Retailers                            | Bán lẻ                                                         |          3 |
| Apparel Retailers                            | Bán lẻ hàng may mặc                                            |          4 |
| Broadline Retailers                          | Bán lẻ phức hợp                                                |          4 |
| Home Improvement Retailers                   | Phân phối nội thất                                             |          4 |
| Specialized Consumer Services                | Dịch vụ tiêu dùng chuyên ngành                                 |          4 |
| Specialty Retailers                          | Phân phối hàng chuyên dụng                                     |          4 |
| Media                                        | Truyền thông                                                   |          2 |
| Media                                        | Truyền thông                                                   |          3 |
| Broadcasting & Entertainment                 | Giải trí & Truyền thông                                        |          4 |
| Media Agencies                               | Dịch vụ truyền thông                                           |          4 |
| Publishing                                   | Sách, ấn bản & sản phẩm văn hóa                                |          4 |
| Travel & Leisure                             | Du lịch và Giải trí                                            |          2 |
| Travel & Leisure                             | Du lịch & Giải trí                                             |          3 |
| Airlines                                     | Dịch vụ hàng không                                             |          4 |
| Gambling                                     | Gambling                                                       |          4 |
| Hotels                                       | Khách sạn                                                      |          4 |
| Recreational Services                        | Dịch vụ giải trí                                               |          4 |
| Restaurants & Bars                           | Nhà hàng và quán bar                                           |          4 |
| Travel & Tourism                             | Vận tải hành khách & Du lịch                                   |          4 |
| Telecommunications                           | Viễn thông                                                     |          1 |
| Telecommunications                           | Viễn thông                                                     |          2 |
| Fixed Line Telecommunications                | Viễn thông cố định                                             |          3 |
| Fixed Line Telecommunications                | Viễn thông cố định                                             |          4 |
| Mobile Telecommunications                    | Viễn thông di động                                             |          3 |
| Mobile Telecommunications                    | Viễn thông di động                                             |          4 |
| Utilities                                    | Tiện ích Cộng đồng                                             |          1 |
| Utilities                                    | Điện, nước & xăng dầu khí đốt                                  |          2 |
| Electricity                                  | Sản xuất & Phân phối Điện                                      |          3 |
| Conventional Electricity                     | Sản xuất & Phân phối Điện                                      |          4 |
| Gas, Water & Multi-utilities                 | Nước & Khí đốt                                                 |          3 |
| Gas Distribution                             | Phân phối xăng dầu & khí đốt                                   |          4 |
| Multiutilities                               | Tiện ích khác                                                  |          4 |
| Water                                        | Nước                                                           |          4 |
| Financials                                   | Tài chính                                                      |          1 |
| Banks                                        | Ngân hàng                                                      |          2 |
| Banks                                        | Ngân hàng                                                      |          1 |
| Banks                                        | Ngân hàng                                                      |          3 |
| Banks                                        | Ngân hàng                                                      |          4 |
| Insurance                                    | Bảo hiểm                                                       |          2 |
| Nonlife Insurance                            | Bảo hiểm phi nhân thọ                                          |          3 |
| Full Line Insurance                          | Bảo hiểm phức hợp                                              |          4 |
| Insurance Brokers                            | Môi giới bảo hiểm                                              |          4 |
| Property & Casualty Insurance                | Bảo hiểm phi nhân thọ                                          |          4 |
| Reinsurance                                  | Tái bảo hiểm                                                   |          4 |
| Life Insurance                               | Bảo hiểm nhân thọ                                              |          3 |
| Life Insurance                               | Bảo hiểm nhân thọ                                              |          4 |
| Real Estate                                  | Bất động sản                                                   |          2 |
| Real Estate Investment & Services            | Bất động sản                                                   |          3 |
| Real Estate Holding & Development            | Bất động sản                                                   |          4 |
| Real Estate Services                         | Tư Vấn, Định giá, Môi giới Bất động sản                        |          4 |
| Real Estate Investment Trusts                | Quỹ ủy thác BĐS                                                |          3 |
| Real Estate Investment Trusts                | Quỹ ủy thác BĐS                                                |          4 |
| Financial Services                           | Dịch vụ tài chính                                              |          2 |
| Financial Services                           | Dịch vụ tài chính                                              |          3 |
| Asset Managers                               | Quản lý tài sản                                                |          4 |
| Consumer Finance                             | Tài chính cá nhân                                              |          4 |
| Specialty Finance                            | Tài chính đặc biệt                                             |          4 |
| Investment Services                          | Môi giới chứng khoán                                           |          4 |
| Mortgage Finance                             | Cầm cố                                                         |          4 |
| Equity Investment Instruments                | Quỹ đầu tư                                                     |          3 |
| Equity Investment Instruments                | Quỹ đầu tư                                                     |          4 |
| Technology                                   | Công nghệ Thông tin                                            |          1 |
| Technology                                   | Công nghệ Thông tin                                            |          2 |
| Software & Computer Services                 | Phần mềm & Dịch vụ Máy tính                                    |          3 |
| Computer Services                            | Dịch vụ Máy tính                                               |          4 |
| Internet                                     | Internet                                                       |          4 |
| Software                                     | Phần mềm                                                       |          4 |
| Technology Hardware & Equipment              | Thiết bị và Phần cứng                                          |          3 |
| Computer Hardware                            | Phần cứng                                                      |          4 |
| Electronic Office Equipment                  | Thiết bị văn phòng                                             |          4 |
| Semiconductors                               | Bán dẫn                                                        |          4 |
| Telecommunications Equipment                 | Thiết bị viễn thông                                            |          4 |
| N/A L4                                       | N/A L4                                                         |          4 |
| Exploration & Production                     | Sản xuất và Khai thác dầu khí                                  |          5 |
| Integrated Oil & Gas                         | Tổ hợp Dầu khí                                                 |          5 |
| Oil Equipment & Services                     | Thiết bị và Dịch vụ Dầu khí                                    |          5 |
| Pipelines                                    | Ống dẫn Dầu                                                    |          5 |
| Alternative Fuels                            | Năng lượng thay thế                                            |          3 |
| Renewable Energy Equipment                   | Thiết bị năng lượng tái chế                                    |          4 |
| Renewable Energy Equipment                   | Thiết bị năng lượng tái chế                                    |          5 |
| Alternative Fuels                            | Nhiên liệu thay thế                                            |          4 |
| Alternative Fuels                            | Nhiên liệu thay thế                                            |          5 |
| Plastics                                     | Nhựa                                                           |          5 |
| Rubber                                       | Cao su                                                         |          5 |
| Synthetic Fibers                             | Sợi tổng hợp                                                   |          5 |
| Commodity Chemicals Wholesale                | Hóa chất cơ bản bán buôn                                       |          5 |
| Other Commodity Chemicals                    | Hóa chất hàng hóa khác                                         |          5 |
| Fertilizer                                   | Phân bón                                                       |          5 |
| Pesticide                                    | Thuốc trừ sâu                                                  |          5 |
| Agricultural Chemicals Wholesale             | Hóa chất nông nghiệp Bán buôn                                  |          5 |
| Forestry                                     | Lâm sản và Chế biến gỗ                                         |          5 |
| Paper                                        | Sản xuất giấy                                                  |          5 |
| Aluminum                                     | Nhôm                                                           |          5 |
| Nonferrous Metals                            | Kim Loại màu                                                   |          5 |
| Producers                                    | Sản xuất, chế biến thép                                        |          5 |
| Metal Merchant Wholesalers                   | Thương mại (Bán buôn) sắt thép                                 |          5 |
| Coal                                         | Khai thác Than                                                 |          5 |
| Diamonds & Gemstones                         | Đá quý và Kim cương                                            |          5 |
| General Mining                               | Khai khoáng                                                    |          5 |
| Gold Mining                                  | Khai thác vàng                                                 |          5 |
| Platinum & Precious Metals                   | Bạch kim & Kim loại quý khác                                   |          5 |
| Other Construction Materials                 | Vật liệu xây dựng khác                                         |          5 |
| Cement                                       | Xi măng                                                        |          5 |
| Concret Manufacturing                        | Sản xuất bê tông                                               |          5 |
| Brick Manufacturing                          | Sản xuất gạch                                                  |          5 |
| Tile & Paving Material Manufacturing         | Sản xuất gạch ốp lát & Vật liệu lát                            |          5 |
| Rock Mining                                  | Khai thác đá                                                   |          5 |
| Paint                                        | Sơn và chất phủ                                             |          5 |
| Construction Material Wholesale              | Vật liệu xây dựng bán buôn                                     |          5 |
| Heavy Construction                           | Xây dựng                                                       |          5 |
| Aerospace                                    | Hàng không                                                     |          5 |
| Defense                                      | Quốc phòng                                                     |          5 |
| Other Containers & Packaging                 | Thùng chứa và bao bì khác                                      |          5 |
| Glass Containers & Packaging                 | Bao bì, đóng gói thủy tinh                                     |          5 |
| Metal Containers & Packaging                 | Bao bì, đóng gói kim loại                                      |          5 |
| Plastic Containers & Packaging               | Bao bì, đóng gói bằng nhựa                                     |          5 |
| Wood Container & Packaging                   | Bao bì, đóng gói từ gỗ                                         |          5 |
| Paper Packaging                              | Bao bì, đóng gói từ giấy                                       |          5 |
| Container & Packaging Material Wholesale     | Vật liệu bao bì, đóng gói bán buôn                             |          5 |
| Diversified Industrials                      | Công nghiệp phức hợp                                           |          5 |
| Electrical Components & Equipment            | Hàng điện & điện tử                                            |          5 |
| Electronic Equipment                         | Thiết bị điện                                                  |          5 |
| Commercial Vehicles & Trucks                 | Xe tải & Đóng tàu                                              |          5 |
| Industrial Machinery                         | Máy công nghiệp                                                |          5 |
| Delivery Services                            | Chuyển phát nhanh                                              |          5 |
| Inland water freight                         | Vận tải nội địa                                                |          5 |
| Deep sea freight                             | Vận tải quốc tế                                                |          5 |
| Railroads                                    | Đường sắt                                                      |          5 |
| Airport                                      | Cảng hàng không                                                |          5 |
| Bus/ Car Station                             | Bến xe khách                                                   |          5 |
| Airport Services                             | Dịch vụ Sân bay                                                |          5 |
| Marine Port Services                         | Dịch vụ cảng biển, cảng sông                                   |          5 |
| Logistics                                    | Dịch vụ kho bãi                                                |          5 |
| Support Activities for Transportation        | Hỗ trợ vận tải                                                 |          5 |
| Cold Trucking                                | Vận tải hàng lạnh                                              |          5 |
| Dry Trucking                                 | Vận tải hàng khô                                               |          5 |
| Business Support Services                    | Tư vấn & Hỗ trợ KD                                             |          5 |
| Business Training & Employment Agencies      | Đào tạo & Việc làm                                             |          5 |
| Financial Administration                     | Quản lý Tài chính                                              |          5 |
| Industrial Suppliers                         | Nhà cung cấp thiết bị                                          |          5 |
| Waste & Disposal Services                    | Chất thải & Môi trường                                         |          5 |
| Automobiles                                  | Sản xuất ô tô                                                  |          5 |
| Auto Parts                                   | Phụ tùng ô tô                                                  |          5 |
| Tires                                        | Lốp xe                                                         |          5 |
| Brewers                                      | Sản xuất bia                                                   |          5 |
| Distillers & Vintners                        | Vang & Rượu mạnh                                               |          5 |
| Other Non-Alcoholic Beverages                | Đồ uống không cồn khác                                         |          5 |
| Tea                                          | Trà                                                            |          5 |
| Coffee                                       | Cafe                                                           |          5 |
| Carbonated Soft Drinks                       | Đồ uống có ga mềm                                              |          5 |
| Cereals Juice                                | Nước ngũ cốc (đậu nành, đậu phộng, vv)                         |          5 |
| Fruit Drinks                                 | Nước trái cây                                                  |          5 |
| Bottled Water & Ice                          | Nước đóng chai                                                 |          5 |
| Fishing                                      | Nuôi trồng thủy hải sản                                        |          5 |
| Pig, Beef & Veal Farming                     | Chăn nuôi gia súc, gia cầm                                     |          5 |
| Grain (Crop), Vegetable, Fruit & Nut Farming | Trồng ngũ cốc, rau, trái cây & hạt                             |          5 |
| Commercial Nurseries                         | Hạt, cây giống thương mại                                      |          5 |
| Coffee, Tea & Cocoa Farming                  | Trồng Cà phê, trà, ca cao                                      |          5 |
| Sugarcane Farming                            | Trồng mía                                                      |          5 |
| Animal Feed                                  | Thức ăn gia súc                                                |          5 |
| Fishing & Farming Wholesale                  | Bán buôn, thu mua nông thủy sản                                |          5 |
| Other Fishing & Farming                      | Nông trại và nuôi trồng khác                                   |          5 |
| Bread, Cracker or Chocolate Confectionery    | Sô cô la, Bánh kẹo, bánh mỳ                                    |          5 |
| Ready made meals                             | Suất ăn công nghiệp                                            |          5 |
| Other Food                                   | Thực phẩm khác                                                 |          5 |
| Fruit & Vegetable Processing                 | Trái cây và rau quả chế biến                                   |          5 |
| Animal Slaughtering & Processing             | Động vật giết mổ và chế biến                                   |          5 |
| Seafood Product Preparation & Packaging      | Hải sản chế biến và đóng gói                                   |          5 |
| Processed food                               | Thực phẩm chế biến                                             |          5 |
| Dairy Products                               | Sản phẩm từ sữa                                                |          5 |
| Starch, Vegetable Fat                        | Tinh bột, rau có chất béo                                      |          5 |
| Sugar                                        | Đường                                                          |          5 |
| Food ingredient, Spices                      | Nguyên liệu chế biến, dầu ăn, gia vị (bột nở, hương liệu, etc) |          5 |
| Durable Household Products                   | Đồ gia dụng lâu bền                                            |          5 |
| Nondurable Household Products                | Đồ gia dụng một lần                                            |          5 |
| Furnishings                                  | Thiết bị gia dụng                                              |          5 |
| Home Construction                            | Xây nhà                                                        |          5 |
| Consumer Electronics                         | Điện tử tiêu dùng                                              |          5 |
| Recreational Products                        | Sản phẩm nghệ thuật                                            |          5 |
| Toys                                         | Đồ chơi                                                        |          5 |
| Clothing & Accessories                       | Hàng May mặc                                                   |          5 |
| Footwear                                     | Giầy dép                                                       |          5 |
| Personal Products                            | Hàng cá nhân                                                   |          5 |
| Tobacco                                      | Thuốc lá                                                       |          5 |
| Health Care Providers                        | Chăm sóc y tế                                                  |          5 |
| Medical Equipment                            | Thiết bị y tế                                                  |          5 |
| Medical Supplies                             | Dụng cụ y tế                                                   |          5 |
| Biotechnology                                | Công nghệ sinh học                                             |          5 |
| Pharmaceuticals                              | Dược phẩm                                                      |          5 |
| Drug Retailers                               | Phân phối dược phẩm                                            |          5 |
| Food Retailers & Wholesalers                 | Phân phối thực phẩm                                            |          5 |
| Apparel Retailers                            | Bán lẻ hàng may mặc                                            |          5 |
| Supermarket                                  | Siêu thị                                                       |          5 |
| Convenience stores                           | Cửa hàng tiện dụng                                             |          5 |
| Hypermarket                                  | Đại siêu thị                                                   |          5 |
| Online                                       | Online                                                         |          5 |
| Other Retailers                              | Các dịch vụ kinh doanh bán lẻ khác                             |          5 |
| Home Improvement Retailers                   | Phân phối nội thất                                             |          5 |
| Specialized Consumer Services                | Dịch vụ tiêu dùng chuyên ngành                                 |          5 |
| Specialty Retailers                          | Phân phối hàng chuyên dụng                                     |          5 |
| Broadcasting & Entertainment                 | Giải trí & Truyền thông                                        |          5 |
| Media Agencies                               | Dịch vụ truyền thông                                           |          5 |
| Publishing                                   | Sách, ấn bản & sản phẩm văn hóa                                |          5 |
| Airlines                                     | Dịch vụ Hàng không                                             |          5 |
| Gambling                                     | Gambling                                                       |          5 |
| Hotels & Resorts                             | Khách sạn, resort                                              |          5 |
| Recreational Services                        | Dịch vụ giải trí                                               |          5 |
| Restaurants & Bars                           | Nhà hàng và quán bar                                           |          5 |
| Road passenger transport                     | Vận tải hành khách đường bộ                                    |          5 |
| Marine Passenger                             | Vận tải hành khách đường thủy                                  |          5 |
| Tourism                                      | Công ty du lịch                                                |          5 |
| Fixed Line Telecommunications                | Viễn thông cố định                                             |          5 |
| Mobile Telecommunications                    | Viễn thông di động                                             |          5 |
| Conventional Electricity                     | Sản xuất & Phân phối Điện                                      |          5 |
| Gas Distribution                             | Phân phối xăng dầu & khí đốt                                   |          5 |
| Multiutilities                               | Tiện ích khác                                                  |          5 |
| Water                                        | Nước                                                           |          5 |
| Traditional Commercial Banks                 | Ngân hàng thương mại truyền thống                              |          5 |
| Fin tech                                     | Fin tech                                                       |          5 |
| Full Line Insurance                          | Bảo hiểm phức hợp                                              |          5 |
| Insurance Brokers                            | Môi giới bảo hiểm                                              |          5 |
| Property & Casualty Insurance                | Bảo hiểm phi nhân thọ                                          |          5 |
| Reinsurance                                  | Tái bảo hiểm                                                   |          5 |
| Life Insurance                               | Bảo hiểm nhân thọ                                              |          5 |
| Other Real Estate Development & Operations   | Phát triển & vận hành Bất động sản khác                        |          5 |
| Office Real Estate Development               | Văn phòng cho thuê                                             |          5 |
| Industrial Real Estate Development           | Bất động sản công nghiệp                                       |          5 |
| Residential Real Estate Development          | Bất động sản dân cư                                         |          5 |
| Other Real Estate Services                   | Dịch vụ Bất động sản khác                                      |          5 |
| Office Real Estate Services                  | Dịch vụ Bất động sản thương mại                                |          5 |
| Retail Real Estate Services                  | Dịch vụ Bất động sản bán lẻ                                    |          5 |
| Industrial Real Estate Services              | Dịch vụ Bất động sản Công nghiệp                               |          5 |
| Residential Real Estate Services             | Dịch vụ Bất động sản dân cư                                    |          5 |
| Real Estate Investment Trusts                | Quỹ ủy thác BĐS                                                |          5 |
| Asset Managers                               | Quản lý tài sản                                                |          5 |
| Consumer Finance                             | Tài chính cá nhân                                              |          5 |
| Specialty Finance                            | Tài chính đặc biệt                                             |          5 |
| Investment Services                          | Môi giới chứng khoán                                           |          5 |
| Mortgage Finance                             | Cầm cố                                                         |          5 |
| Equity Investment Instruments                | Quỹ đầu tư                                                     |          5 |
| Computer Services                            | Dịch vụ Máy tính                                               |          5 |
| Internet                                     | Internet                                                       |          5 |
| Software                                     | Phần mềm                                                       |          5 |
| Computer Hardware                            | Phần cứng                                                      |          5 |
| Electronic Office Equipment                  | Thiết bị văn phòng                                             |          5 |
| Semiconductors                               | Bán dẫn                                                        |          5 |
| Telecommunications Equipment                 | Thiết bị viễn thông                                            |          5 |
| N/A L5                                       | N/A L5                                                         |          5 |
| N/A L1                                       | N/A L1                                                         |          1 |
| N/A L2                                       | N/A L2                                                         |          2 |
| N/A L3                                       | N/A L3                                                         |          3 |


# Truy xuất dữ liệu

Các ví dụ liên quan đến việc truy xuất dữ liệu lịch sử

## Truy xuất dữ liệu lịch sử

```python
from FiinQuantX import FiinSession
# Đăng nhập
username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

client = FiinSession(username=username, password=password).login()
fi = client.FiinIndicator()
# Lấy dữ liệu có sẵn
tickers = ['HPG','SSI','VN30'] 
df = client.Fetch_Trading_Data(
    realtime = False,
    tickers = tickers,    
    fields = ['open','high','low','close','volume','bu','sd','fn','fs','fb'],
    adjusted=True,
    from_date='2024-12-04',
    by = '1m'
    ).get_data()

print(df)
```

```
 fields = ['open','high','low','close','volume','bu','sd','fn','fs','fb']
```

Giải thích các trường dữ liệu:

* open,high,low,close: Đại diện cho giá Open, High, Low, Close
* volume: Đại diện cho khối lượng khớp lệnh (Volume)
* bu,sd: Chỉ số mua bán chủ động
* fn,fs,fb: là Foreign Net, Foreign Sell, Foreign Buy, giá trị nhà đầu tư nước ngoài mua bán ròng, mua hoặc bán.

## Truy xuất dữ liệu Realtime

```python
import time
import pandas as pd

from FiinQuantX import FiinSession, RealTimeData

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

fi = client.FiinIndicator()
df = []
tickers = ['SSI','ITC','HPG','VHM']
for i in range(len(tickers)):
    df.append(pd.DataFrame())
df_total = pd.DataFrame()
def onEvent(data: RealTimeData):
    global df_total
    df_total = pd.concat([df_total, data.to_dataFrame()],ignore_index=True)
    df_total.to_csv('data.csv', index = False)
    for i in range(len(tickers)):
        if data.Ticker == tickers[i]:
            print(data.Ticker, data.Close)
            df[i] = pd.concat([df[i], data.to_dataFrame()],ignore_index=True)
            print(df[i])

TickerEvents = client.Trading_Data_Stream(tickers=tickers, callback = onEvent)
TickerEvents.start()
try:
    while not TickerEvents._stop:
        time.sleep(1)
except KeyboardInterrupt:
    print("KeyboardInterrupt received, stopping...")
    TickerEvents.stop()

```

## 3. Tìm khối lượng mua bán ATC của VN30

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F1em57BsQEhzLuZMpEGCR%2Fimage.png?alt=media&amp;token=698eca42-5f43-4e56-bcc1-45e4a1d2bf79" alt=""><figcaption><p>VN30 khối lượng ATC</p></figcaption></figure>

```python

import pandas as pd
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

VN30 = [
    'ACB', 'BCM', 'BID', 'BVH', 'CTG', 'FPT', 'GAS', 'GVR', 'HDB', 'HPG', 
    'LPB', 'MBB', 'MSN', 'MWG', 'PLX', 'SAB', 'SHB', 'SSB', 'SSI', 'STB', 
    'TCB', 'TPB', 'VCB', 'VHM', 'VIB', 'VIC', 'VJC', 'VNM', 'VPB', 'VRE']
 

data = client.Fetch_Trading_Data(
    tickers=VN30,
    fields=['fn', 'fs', 'fb'],
    adjusted=True,
    period=10,
    realtime=False,
    by='1m',
).get_data()

filtered_data = data[data['timestamp'].str.endswith('14:45')]
filtered_data.to_excel('filtered_data.xlsx', index=False)
print("Data stored in filtered_data.xlsx")
```


# Truy xuất và lưu dữ liệu realtime lên Google Sheet

Các ví dụ liên quan đến việc truy xuất dữ liệu realtime và lưu lên Google Sheet

## Tạo và tải khóa tài khoản dịch vụ Google JSON

Đi đến Google Cloud Console: <https://console.cloud.google.com/>

Chọn hoặc tạo một project mới, nếu không có project nào click "New Project".

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FnqBflusX4ArFsxArRgaR%2Fimage.png?alt=media&amp;token=fc19d15c-9ac5-4952-9f19-daa43a70d2f7" alt=""><figcaption></figcaption></figure>

Đi đến mục **APIs & Services > Library**

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FO45MmUZUSVFXVnkqKy1w%2Fimage.png?alt=media&amp;token=58ca3a75-84bc-4e2e-b5de-80b3ffd01222" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2Fpkjjev2IS7JnXV80Jy3S%2Fimage.png?alt=media&amp;token=55499bdf-74b6-407e-9e51-ba3bbf5c81e7" alt=""><figcaption></figcaption></figure>

Chọn mục **Google Sheets API**

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FV0yTYii28ZBSuzeXOpCr%2Fimage.png?alt=media&amp;token=f27fa1f7-cbef-4f73-81b1-65e2da6c181f" alt=""><figcaption></figcaption></figure>

Enable API

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FWQJAttFYG9pEzft8CC6K%2Fimage.png?alt=media&amp;token=14e2ee42-e80d-4a04-9c4d-10fa53fcca81" alt=""><figcaption></figcaption></figure>

Truy cập vào mục **IAM & Admin > Service Accounts**, click **"Create Service Account"**, thực hiện đặt tên chp Service Account rồi click "Create and Continue"

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FbK9SCAbtHrH8b2kW1ADB%2Fimage.png?alt=media&amp;token=1a464def-f807-42d6-aac8-efa2b27d5be7" alt=""><figcaption></figcaption></figure>

Chọn role cho Service Account (Editor) và click Continue

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FtxtHpLREbq4E6hYCAZXt%2Fimage.png?alt=media&amp;token=375bdfcd-3192-4663-9380-fbb6db904ebf" alt=""><figcaption></figcaption></figure>

Sau khi tạo Service Account, click vào tên Service Account mới tạo, đi đến tab **"Keys"**, click **"Add Key" > "Create new key"**, chọn **JSON** và click **"Create"**. Sau đó trình duyệt sẽ tải file JSON cấu hình để truy cập vào Google Sheet tự động. Sau đó hãy di chuyển file JSON vừa tải về đến cùng folder với file Python viết code Truy xuất data từ FiinQuant và lưu lên Google Sheets.

Sau đó thực hiện truy cập vào file Google Sheets cần load data lên, thực hiện add quyền edit cho email ở mục **client\_email** của file JSON vừa tải về. Sau đó thực hiện đoạn code sau

<pre class="language-python"><code class="lang-python">import os
import gspread
import time
import pandas as pd

from FiinQuantX import FiinSession, RealTimeData
from gspread_dataframe import set_with_dataframe
from oauth2client.service_account import ServiceAccountCredentials

username = "REPLACE_WITH_YOUR_USERNAME"
password = "REPLACE_WITH_YOUR_PASSWORD"

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

def OnTickerEvent(data: RealTimeData):
    global full_df
    df = data.to_dataFrame()
    
    # Xác thực và kết nối đến Google Sheets
    scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
    creds = ServiceAccountCredentials.from_json_keyfile_name("REPLACE_WITH_JSON_FILE_NAME")
    client = gspread.authorize(creds)

    # Mở Google Sheet và chọn worksheet
    sheet = client.open("REPLACE_WITH_YOUR_GOOGLE_SHEET_FILE_NAME").worksheet("REPLACE_WITH_SHEET_NAME")

    # Thêm data vào Google Sheet ---
    existing_rows = len(sheet.get_all_values())  # Đếm số cột hiện có
    
    # Nếu chưa có cột nào thêm data mới bao gồm cả tiêu đề cột, nếu không chỉ thêm data, không thêm tiêu đề cột
    if existing_rows &#x3C;= 1:
        set_with_dataframe(sheet, df, row=existing_rows, include_column_header=True)
    else:
        set_with_dataframe(sheet, df, row=existing_rows + 1, include_column_header=False)

<strong>tickers = ['STB', 'FPT', 'MSN', 'HPG']
</strong>
event = client_fq.Trading_Data_Stream(tickers=tickers, callback=OnTickerEvent)
event.start()

try:
    while not event._stop: 
        time.sleep(1)
except KeyboardInterrupt:
    print("KeyboardInterrupt received, stopping...")
    event.stop()


</code></pre>


# Mô hình tín hiệu

### 1. Xây dựng bot tín hiệu cảnh báo

**Mục đích:** Xây dựng bot trên nền tảng Telegram, giúp cảnh báo các biến động về mua bán chủ động và giao dịch nhà đầu tư nước ngoài.

**Kết quả khi chạy bot:**

![](https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FeT79Tk0mQRjc7GBBrOkg%2Fimage.png?alt=media\&token=0a49e57a-cc78-481d-ac4c-850e88a7b9d3)&#x20;

Các bước chuẩn bị:

* Tạo bot trên telegram, bằng cách BotFather trên ứng dụng Telegram'
* <https://telegram.me/BotFather>

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FydVpokrTkGElsEmYSStY%2Fimage.png?alt=media&amp;token=3037e781-8a57-46a4-825c-9e9f237dd94f" alt=""><figcaption></figcaption></figure>

* Sau khi tạo bot xong lưu API Token

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F6Cmguc60aJgNZXwS9OvW%2Fimage.png?alt=media&amp;token=b0183048-9105-482d-8d8c-cfc87a3645c3" alt=""><figcaption></figcaption></figure>

* Tạo 1 group chat trên Telegram trong đó invite chatbot vừa tạo làm thành viên
* Bật chọn tính năng Topics (On) trên setting của group vừa tạo

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FSrwu682HoWrKdPDIwCke%2Ftelegram-cloud-photo-size-5-6190552255007146444-y.jpg?alt=media&amp;token=b7f10493-c1f4-406c-a255-d803a286d4cb" alt="" width="250"><figcaption></figcaption></figure>

Sau khi tạo xong, người dùng sẽ thấy chữ **Create a topic,  cần tạo các chủ đề (threadid) liên quan, mỗi topic sẽ có 1 thread id riêng.**

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FCn3kr8hCqwljPjcMdd1i%2Ftelegram-cloud-photo-size-5-6190552255007146445-y.jpg?alt=media&amp;token=be8f5007-2dfd-48b2-a207-602d8359d7c3" alt="" width="259"><figcaption></figcaption></figure>

Truy cập đường link <https://web.telegram.org/>, đăng nhập bằng tài khoản telegram của người dùng.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FGH6bR9TbiT9wqqglG0WS%2Fimage.png?alt=media&amp;token=61ec85ce-34e0-421c-a9f7-b6f06c708829" alt=""><figcaption></figcaption></figure>

Như vậy sau 3 bước trên, người dùng sẽ có các thông tin sau:

1. API Token của bot
2. Topic ID
3. ThreadID

Kết hợp với thông tin về Username và Password, điền vào code mẫu bên dưới để thực hiện kích hoạt bot

````python
import time
import requests

from FiinQuantX import FiinSession, BarDataUpdate
from datetime import datetime
from typing import Union, List

# ===== 1. KẾT NỐI API FIINQUANT =====
username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

# ===== 2. CLASS GỬI TELEGRAM =====
class TelegramNotifier:
    def __init__(self, bot_token: str, chat_id: str, thread_id: str = None):
        self.bot_token = bot_token
        self.chat_id = chat_id
        self.thread_id = thread_id
 
    def send_message(self, text: str):
        """Gửi tin nhắn Telegram."""
       
        if not self.bot_token or not self.chat_id:
            print("⚠ Lỗi: Chưa cấu hình Telegram!")
            return
        start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(f"📤 Bắt đầu gửi tin nhắn lúc: {start_time}")
        url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage"
        payload = {
            "chat_id": self.chat_id,
            "text": text,
            "parse_mode": "HTML"
        }
        if self.thread_id:
            payload["message_thread_id"] = self.thread_id  # Nếu có THREAD_ID, thêm vào
 
        try:
            response = requests.post(url, data=payload, timeout=5)
            response.raise_for_status()
            print("📩 Đã gửi tin nhắn Telegram thành công!")
        except requests.exceptions.RequestException as e:
            print(f"❌ Lỗi gửi Telegram: {response.status_code} - {response.json()}"
)
 
# ===== 3. CLASS CẢNH BÁO NĐTNN =====
class ForeignWarning:
    def __init__(self, tickers: List[str], timeframe: str, N: int, X: int):
        self.tickers = tickers
        self.timeframe = timeframe
        self.Config = {"N": N, "X": X}
        self.foreign_telegram_notifier = TelegramNotifier('API_TELEGRAM_TOKEN', 'GROUPID', 'THREADID')
        self.busd_telegram_notifier = TelegramNotifier('API_TELEGRAM_TOKEN', 'GROUDID', 'THREADID')
        self.last_timestamp = None  # Lưu timestamp gần nhất
        self.foreign_warned_ticker_times = {}  # Tránh cảnh báo trùng GDNN
        self.busd_warned_ticker_times = {} # Tránh cảnh báo trùng BUSD
        self.data_yesterday = client.Fetch_Trading_Data(
            realtime=False,
            tickers=tickers,    
            fields=['close'],
            adjusted=True,
            by='1d',
            period=1
        ).get_data()
        print(self.data_yesterday)
    def _fetch_realtime_data(self, callback):
        """Lấy dữ liệu giao dịch real-time."""
        event = client.Fetch_Trading_Data(
            realtime=True,
            tickers=self.tickers,
            fields=["close","fn","bu","sd"],
            adjusted=True,
            period=self.Config["X"] + 2,
            by=self.timeframe,
            callback=callback,
            wait_for_full_timeFrame=False
        )
        event.get_data()
        try:
            while not event._stop:
                time.sleep(1)
        except KeyboardInterrupt:
            print("⛔ Dừng theo dõi dữ liệu...")
            event.stop()
 
    def _process_data(self, data: BarDataUpdate):
        """Xử lý dữ liệu và xác định cảnh báo."""
        df = data.to_dataFrame()
 
        # Bỏ cây nến lúc 14:45 nếu timeframe là 1M và 5M
        if self.timeframe in ["1m", "5m"]:
            df = df[~df["timestamp"].str.contains("14:45")]
 
        ticker = df.iloc[-2]["ticker"]
        timestamp = df.iloc[-2]["timestamp"]
        close_price = df.iloc[-2]["close"]  # Giá đóng cửa của nến trước 
        # Tính các chỉ số GDNN
        FNet = df.iloc[-2]["fn"]
        FNetPrev = df.iloc[-3]["fn"]
 
        #Tính các chỉ số BUSD
        BUSD = df.iloc[-2]["bu"] - df.iloc[-2]["sd"]
        BUSDratio = df.iloc[-2]["bu"] / df.iloc[-2]["sd"] if df.iloc[-2]["sd"] != 0 else float("inf")
        BUSDPrev = df.iloc[-3]["bu"] - df.iloc[-3]["sd"]
 
        # Lấy dữ liệu trung bình X timeframe gần nhất
        df_x = df.iloc[0:-2]
 
        # Tính GDNN mua và bán lơn nhất trong lịch sử
        FNetMax = df_x["fn"].max() if not df_x.empty else 0
        FNetMin = df_x["fn"].min() if not df_x.empty else 0
 
        # Tính GDNN mua và bán lơn nhất trong lịch sử
        BUSDMax = (df_x["bu"] - df_x["sd"]).max() if not df_x.empty else 0
        BUSDMin = (df_x["bu"] - df_x["sd"]).min() if not df_x.empty else 0

        # Lấy giá đóng cửa ngày hôm qua từ data_yesterday
        close_yesterday = self.data_yesterday.loc[self.data_yesterday['ticker'] == ticker, 'close'].values

        # Kiểm tra xem có dữ liệu hôm qua không
        if len(close_yesterday) > 0:
            close_yesterday = close_yesterday[0]  # Lấy giá trị đầu tiên
            price_return = ((close_price - close_yesterday) / close_yesterday) * 100
        else:
            price_return = None  # Không có dữ liệu hôm qua thì không tính được

 
        # Nếu mua mạnh
        if FNet > 500000000:
            if FNet > self.Config["N"] * FNetPrev and FNet > 1.3*FNetMax and timestamp != self.foreign_warned_ticker_times.get(ticker):
                if price_return is not None:
                    price_change_text = f"(tăng {price_return:.2f}%)" if price_return > 0 else f"(giảm {abs(price_return):.2f}%)"
                else:
                    price_change_text = ""  # Không có dữ liệu hôm qua thì không hiển thị gì
                msg = (f"📈 <b>CẢNH BÁO: {ticker}</b>\n"
                    f"- NĐTNN <b>mua vào mạnh</b>: {FNet / 1_000_000:.2f} triệu VND trong 1'\n"
                    f"- <b>Giá đóng cửa:</b> {close_price:.0f} {price_change_text}\n"
                    f"- <b>Thời gian</b>: {timestamp}")
                self.foreign_warned_ticker_times[ticker] = timestamp  # Lưu ticker đã cảnh báo
                print(msg)
 
                self.foreign_telegram_notifier.send_message(msg)
 
        # Nếu bán mạnh
        elif FNet < -2000000000:
            if FNet < self.Config["N"] * FNetPrev and FNet < 1.3*FNetMin and timestamp != self.foreign_warned_ticker_times.get(ticker):
                if price_return is not None:
                    price_change_text = f"(tăng {price_return:.2f}%)" if price_return > 0 else f"(giảm {abs(price_return):.2f}%)"
                else:
                    price_change_text = ""  # Không có dữ liệu hôm qua thì không hiển thị gì
                msg = (f"📉 <b>CẢNH BÁO: {ticker}</b>\n"
                    f"- NĐTNN <b>bán ra mạnh</b>: {abs(FNet) / 1_000_000:.2f} triệu VND trong 1'\n"
                    f"- <b>Giá đóng cửa:</b> {close_price:.0f} {price_change_text}\n"
                    f"- <b>Thời gian</b>: {timestamp}")
                self.foreign_warned_ticker_times[ticker] = timestamp  # Lưu ticker đã cảnh báo
                print(msg)
 
                self.foreign_telegram_notifier.send_message(msg)
 
        # Cảnh báo với BUSD
        if BUSD > 10000:  # Mua mạnh
            if BUSD > self.Config["N"] * BUSDPrev and BUSD > 1.3*BUSDMax and timestamp != self.busd_warned_ticker_times.get(ticker):
                print(f'Các mã đã cảnh báo: {self.busd_warned_ticker_times}')
                # Format lại price_return để chỉ hiển thị tăng/giảm %
                if price_return is not None:
                    price_change_text = f"(tăng {price_return:.2f}%)" if price_return > 0 else f"(giảm {abs(price_return):.2f}%)"
                else:
                    price_change_text = ""  # Không có dữ liệu hôm qua thì không hiển thị gì
                msg = (f"- <b>📈 {ticker} - MUA CHỦ ĐỘNG tăng mạnh </b>\n"
                       f"- <b>Giá đóng cửa:</b> {close_price:.0f} {price_change_text}\n"
                       f"- BU-SD = {BUSD / 1_000:.2f} nghìn CP trong 1'\n"
                       f"- <b>Tương quan BU/SD</b>: {BUSDratio:.2f} lần \n"
                       f"- <b>Thời gian</b>: {timestamp}")
                self.busd_warned_ticker_times[ticker] = timestamp
                print(msg)
                self.busd_telegram_notifier.send_message(msg)
       
        elif BUSD < -10000:  # Bán mạnh
            if BUSD < self.Config["N"] * BUSDPrev and BUSD < 1.3*BUSDMin and timestamp != self.busd_warned_ticker_times.get(ticker):
                print(f'Các mã đã cảnh báo: {self.busd_warned_ticker_times}')
                if price_return is not None:
                    price_change_text = f"(tăng {price_return:.2f}%)" if price_return > 0 else f"(giảm {abs(price_return):.2f}%)"
                else:
                    price_change_text = ""  # Không có dữ liệu hôm qua thì không hiển thị gì
                msg = (f"- <b>📉 {ticker} BÁN CHỦ ĐỘNG tăng mạnh </b>\n"
                       f"- BU-SD = {-(BUSD) / 1_000:.2f} nghìn CP trong 1'\n"
                       f"- <b>Giá đóng cửa:</b> {close_price:.0f} {price_change_text}\n"
                       f"- <b>Tương quan SD/BU</b>: {1/BUSDratio:.2f} lần \n"
                       f"- <b>Thời gian</b>: {timestamp}")
                self.busd_warned_ticker_times[ticker] = timestamp
                print(msg)
 
                self.busd_telegram_notifier.send_message(msg)
   
    def run(self):
        """Chạy hệ thống cảnh báo."""
        self._fetch_realtime_data(self._process_data)
 
# ===== 4. HÀM GIAO TIẾP VỚI NGƯỜI DÙNG =====
def user_input():
    """Hàm lấy thông tin cấu hình từ người dùng."""
    VN30 = [
    'STB', 'FPT', 'MSN', 'HPG', 'EVF',
    'MWG', 'EIB', 'VHM', 'DBC', 'DGC',
    'HDB', 'SSI', 'TCB', 'MBB', 'ACB',
    'VTP', 'VCB', 'HCM', 'VPI', 'VPB',
    'SZC', 'VIX', 'CTG', 'BID', 'HAH',
    'DIG', 'LGC', 'DXG', 'POW', 'HDG',
    'VIC', 'HVN', 'VN30F1M', 'BMP', 'TPB',
    'KDC', 'BAF', 'PVS', 'YEG', 'HAG',
    'VNM', 'HSG', 'LPB', 'PDR','VRE',
    'VOS', 'SHB', 'NTP','TNH','HNG']
    default_params = {
        "timeframe": "1m", #timeframe 1'
        "N": 5, #lớn hơn 5 lần nến gần nhất.
        "X": 500 # lớn nhất trong 300 nến gần nhất
    }
 
    print("\n🚀 Chào mừng đến hệ thống cảnh báo GDNN theo THỜI GIAN THỰC của FIINQUANT 🚀\n")
    print(f"📌 Sử dụng tham số mặc định: {default_params}")
 
    use_default = input("Bạn có muốn dùng tham số mặc định không? (y/n): ").strip().lower() == "y"
   
    if not use_default:
        tickers = input("Nhập danh sách mã cổ phiếu (mặc định: VN30, phân tách bằng dấu phẩy): ").replace(' ', '').split(',')
        timeframe = input("Nhập khung thời gian (mặc định: 1m): ").strip() or default_params["timeframe"]
        N = int(input("Nhập số lần giá trị lớn hơn timeframe trước đó (mặc định: 5): ") or default_params["N"])
        X = int(input("Nhập số timeframe trung bình để so sánh (mặc định: 100): ") or default_params["X"])
    else:
        tickers = VN30
        timeframe = default_params["timeframe"]
        N, X = default_params["N"], default_params["X"]
        
 
    telegram_signal = input("Gửi tín hiệu Telegram? (y/n): ").strip().lower() == "y"
    #bot_token = input("Nhập BOT TOKEN Telegram: ") if telegram_signal else None
    #chat_id = input("Nhập Chat ID Telegram: ") if telegram_signal else None
    #thread_id = input("Nhập THREAD ID (nếu có): ") if telegram_signal else None
 
 
    # Khởi chạy cảnh báo
    ForeignWarning(tickers, timeframe, N, X).run()
 
# ===== 5. CHẠY CHƯƠNG TRÌNH =====
if __name__ == "__main__":
    user_input()
```
````


# Mô hình định lượng

## 1. Tìm các điểm Pivot Point và Price Channel&#x20;

{% hint style="info" %}
Các điểm Pivot Point là mức giá quan trọng được tính toán dựa trên giá cao nhất (high), giá thấp nhất (low) và giá đóng cửa (close) của phiên giao dịch trước đó. Nó được sử dụng để xác định các mức hỗ trợ và kháng cự tiềm năng.\
\
Stock channel hay **kênh giá** là một phạm vi giá mà cổ phiếu dao động trong một khoảng thời gian nhất định. Kênh giá giúp xác định xu hướng hiện tại của thị trường. Có ba loại kênh giá phổ biến:

1. **Kênh giá tăng (Ascending Channel)** – Giá dao động trong một xu hướng tăng với mức đáy và đỉnh cao dần.
2. **Kênh giá giảm (Descending Channel)** – Giá dao động trong xu hướng giảm với mức đáy và đỉnh thấp dần.
3. **Kênh giá ngang (Sideways Channel)** – Giá dao động trong một phạm vi hẹp, không có xu hướng rõ ràng.

Kênh giá được xác định bằng hai đường trendline:

* **Trendline trên** kết nối các đỉnh
* **Trendline dưới** kết nối các đáy

Khi giá chạm vào đường trendline trên hoặc dưới, nó có thể phản ứng theo hai cách:

* **Bật ngược lại** nếu kênh giá tiếp tục giữ.
* **Phá vỡ (Breakout)** nếu xu hướng thay đổi, có thể dẫn đến sự hình thành một kênh giá mới.

Stock channels thường được sử dụng để tìm điểm vào lệnh mua ở vùng hỗ trợ và bán ở vùng kháng cự.
{% endhint %}

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FUoh4yDKYo67MTSzy6Psg%2Fimage.png?alt=media&amp;token=2a94758a-8c2d-4084-9c2b-fdecf32adb54" alt=""><figcaption><p>Pivot Point (điểm màu tím)  trong dữ liệu lích sử giá của VCB </p></figcaption></figure>

**Lấy Historical data từ thư viện Fiinquant**

```python
import pandas as pd
import numpy as np
import plotly.graph_objects as go

from scipy import stats
from FiinQuantX import FiinSession

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

data = client.Fetch_Trading_Data(
    tickers='VCB',
    fields=['open', 'high', 'low', 'close', 'volume'],
    adjusted=True,
    period=1000,
    realtime=False,
    by='1d',
).get_data()

```

**TÌm Pivot Point và plot giá cổ phiếu**

```python
# Function to identify pivot points in price data
# Returns: 0 for no pivot, 1 for pivot high, 2 for pivot low, 3 for both
# Parameters:
#   candle: index of the current candle being checked
#   window: number of candles to check on either side
def isPivot(candle, window):
    if candle-window < 0 or candle+window >= len(data):
        return 0
    
    pivotHigh = 1
    pivotLow = 2
    for i in range(candle-window, candle+window+1):
        if data.iloc[candle].low > data.iloc[i].low:
            pivotLow=0
        if data.iloc[candle].high < data.iloc[i].high:
            pivotHigh=0
    if (pivotHigh and pivotLow):
        return 3
    elif pivotHigh:
        return pivotHigh
    elif pivotLow:
        return pivotLow
    else:
        return 0

# Apply isPivot function to each row of data
window=10
data['isPivot'] = data.apply(lambda x: isPivot(x.name,window), axis=1)

# Function to determine plotting position for pivot points
# Returns slightly offset values for visual clarity on the chart
# Parameters:
#   x: row of dataframe containing price and pivot information
def pointpos(x):
    if x['isPivot']==2:
        return x['low']-1e-3  # Offset below pivot low
    elif x['isPivot']==1:
        return x['high']+1e-3 # Offset above pivot high
    else:
        return np.nan

# Apply pointpos function to create plotting positions
data['pointpos'] = data.apply(lambda row: pointpos(row), axis=1)


# Create candlestick chart
dfpl = data.copy()
fig = go.Figure(data=[go.Candlestick(x=dfpl.index,
                open=dfpl['open'],
                high=dfpl['high'],
                low=dfpl['low'],
                close=dfpl['close'])])

fig.add_scatter(x=dfpl.index, y=dfpl['pointpos'], mode="markers",
                marker=dict(size=5, color="MediumPurple"),
                name="pivot")
                
fig.update_layout(xaxis_rangeslider_visible=False)

fig.show()
```

**Tìm Price Channel dựa trên Pivot Point**&#x20;

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FnQK3QkkIrMRrR3x0TfI9%2Fimage.png?alt=media&amp;token=02a8ad0d-c73b-44fd-b2ff-bd2b52a89093" alt=""><figcaption><p>Một đoạn Sideway Channel </p></figcaption></figure>

```python
# Function to identify and calculate channel slopes using pivot points
# Parameters:
#   candle: Current candle position to analyze from
#   backcandles: Number of previous candles to look back
#   window: Window size for pivot point calculation
def collect_channel(candle, backcandles, window):
    # Get subset of data for analysis
    localdf = data[candle-backcandles-window:candle-window]
    localdf['isPivot'] = localdf.apply(lambda x: isPivot(x.name,window), axis=1)
    
    # Extract pivot highs and lows with their indices
    highs = localdf[localdf['isPivot']==1].high.values
    idxhighs = localdf[localdf['isPivot']==1].high.index
    lows = localdf[localdf['isPivot']==2].low.values
    idxlows = localdf[localdf['isPivot']==2].low.index
    
    # Calculate regression lines if enough pivot points exist
    if len(lows)>=2 and len(highs)>=2:
        # Calculate regression for lower channel (pivot lows)
        sl_lows, interc_lows, r_value_l, _, _ = stats.linregress(idxlows,lows)
        # Calculate regression for upper channel (pivot highs)
        sl_highs, interc_highs, r_value_h, _, _ = stats.linregress(idxhighs,highs)
    
        return(sl_lows, interc_lows, sl_highs, interc_highs, r_value_l**2, r_value_h**2)
    else:
        return(0,0,0,0,0,0)

# Set parameters for channel analysis
candle = 200          # Current candle position
backcandles = 100     # Number of candles to look back
window = 3            # Window size for pivot calculation

# Create candlestick chart
fig = go.Figure(data=[go.Candlestick(x=dfpl.index,
                open=dfpl['open'],
                high=dfpl['high'],
                low=dfpl['low'],
                close=dfpl['close'])])

# Add pivot points to chart
fig.add_scatter(x=dfpl.index, y=dfpl['pointpos'], mode="markers",
                marker=dict(size=5, color="MediumPurple"),
                name="pivot")

# Calculate channel slopes and angles
sl_lows, interc_lows, sl_highs, interc_highs, r_sq_l, r_sq_h = collect_channel(candle, backcandles, window)
print(sl_lows,sl_highs)
angle_lows = np.degrees(np.arctan(sl_lows))
angle_highs = np.degrees(np.arctan(sl_highs))

# Plot channel lines
x = np.array(range(candle-backcandles-window, candle+1))
fig.add_trace(go.Scatter(x=x, y=sl_lows*x + interc_lows, mode='lines', name='lower slope'))
fig.add_trace(go.Scatter(x=x, y=sl_highs*x + interc_highs, mode='lines', name='max slope'))
fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()
```

## 2. Thống kê các giai đoạn tăng giá của VN-Index

Thông số có thể thay đổi:

Nếu đổi percent từ 5.0 lên 10.0 sẽ lọc những giai đoạn thị trường chỉnh nhiều hơn

```python
df["zigzag"] = zigzag_percent(df["high"], df["low"], df["close"], percent=5.0)
```

Fulll Code

```python
# Thống kê các giai đoạn giá tăng VNINDEX bằng ZigZag tự code (pivot chỉ tại điểm đảo chiều)
from FiinQuantX import FiinSession
import pandas as pd

# 1) Đăng nhập
client = FiinSession(username="YOUR_USER", password="YOUR_PASS").login()

# 2) Lấy dữ liệu VNINDEX (giá từ FiinQuant)
event = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["VNINDEX"],
    fields=["high", "low", "close"],
    adjusted=True,
    by="1d",
    period=1500  # ~6 năm, tùy chỉnh
)
df = event.get_data().reset_index(drop=True)

# 3) ZigZag theo % đảo chiều: chỉ gắn pivot khi đảo chiều >= threshold
def zigzag_percent(high: pd.Series, low: pd.Series, close: pd.Series, percent: float = 5.0) -> pd.Series:
    thr = percent / 100.0
    n = len(close)
    pivots = [None] * n

    # Trạng thái
    trend = 0          # 0: chưa xác định, 1: up, -1: down
    start_idx = 0
    start_px = close.iloc[0]
    extreme_idx = 0    # chỉ số của đỉnh/đáy cực trị trong xu hướng hiện tại
    extreme_px = close.iloc[0]

    for i in range(1, n):
        px = close.iloc[i]

        if trend == 0:
            # Chờ giá đi đủ biên để xác nhận hướng ban đầu
            if px >= start_px * (1 + thr):
                trend = 1
                extreme_idx, extreme_px = i, px
            elif px <= start_px * (1 - thr):
                trend = -1
                extreme_idx, extreme_px = i, px
            else:
                # chưa đủ biên, tiếp tục theo dõi, cập nhật cực trị tạm
                if px > extreme_px:
                    extreme_idx, extreme_px = i, px
                if px < extreme_px:
                    extreme_idx, extreme_px = i, px
            continue

        if trend == 1:
            # Đang uptrend: cập nhật đỉnh cực trị
            if px > extreme_px:
                extreme_idx, extreme_px = i, px
            # Đảo chiều đủ biên → chốt pivot tại đỉnh cực trị trước đó
            elif px <= extreme_px * (1 - thr):
                pivots[extreme_idx] = extreme_px  # pivot tại reversal
                trend = -1
                extreme_idx, extreme_px = i, px   # bắt đầu theo dõi đáy mới
        else:  # trend == -1
            # Đang downtrend: cập nhật đáy cực trị
            if px < extreme_px:
                extreme_idx, extreme_px = i, px
            # Đảo chiều đủ biên → chốt pivot tại đáy cực trị trước đó
            elif px >= extreme_px * (1 + thr):
                pivots[extreme_idx] = extreme_px
                trend = 1
                extreme_idx, extreme_px = i, px

    # Chốt pivot cuối cùng tại cực trị hiện tại (tùy chọn)
    pivots[extreme_idx] = extreme_px
    return pd.Series(pivots, index=close.index, name="zigzag")

# 4) Áp dụng ZigZag và tạo bảng các đoạn TĂNG
df["zigzag"] = zigzag_percent(df["high"], df["low"], df["close"], percent=5.0)

turn_points = df.dropna(subset=["zigzag"]).reset_index()  # chỉ còn các pivot tại điểm đảo chiều
uptrends = []

for i in range(1, len(turn_points)):
    i0 = turn_points.loc[i-1, "index"]
    i1 = turn_points.loc[i, "index"]
    p0 = turn_points.loc[i-1, "zigzag"]
    p1 = turn_points.loc[i, "zigzag"]

    if p1 > p0:  # đoạn tăng là từ pivot đáy → pivot đỉnh tiếp theo
        uptrends.append({
            "StartIndex": i0,
            "EndIndex": i1,
            "StartDate": df.loc[i0, "timestamp"],
            "EndDate": df.loc[i1, "timestamp"],
            "LengthInBars": i1 - i0,
            "StartPrice": float(p0),
            "EndPrice": float(p1),
            "PctChange": (p1 - p0) / p0 * 100.0
        })

uptrend_df = pd.DataFrame(uptrends)
# Ví dụ lọc các đợt tăng đủ dài và mạnh
# uptrend_df = uptrend_df[(uptrend_df["LengthInBars"] >= 20) & (uptrend_df["PctChange"] >= 10)]

print(uptrend_df.sort_values("StartIndex").reset_index(drop=True))
```

## 3. Thống kê diễn biến các phiên trước nghỉ lễ

```python
from FiinQuantX import FiinSession
import pandas as pd
from datetime import datetime, timedelta

client = FiinSession(username= 'USERNAME', password='PASSWORD').login()
# Hàm truy xuất 10 phiên trước 2/9 của mỗi năm
def get_last_sessions_before_sep2(year, n=10):
    to_date = f"{year}-09-01"
    from_date = (datetime.strptime(to_date, "%Y-%m-%d") - timedelta(days=30)).strftime("%Y-%m-%d")

    event = client.Fetch_Trading_Data(
        realtime=False,
        tickers=["VNINDEX"],
        fields=["close"],
        adjusted=True,
        by="1d",
        from_date=from_date,
        to_date=to_date
    )
    df = event.get_data().sort_values("timestamp").reset_index(drop=True)
    df = df.tail(n).copy()
    df["return"] = df["close"].pct_change() * 100  # Tính % thay đổi
    df["label"] = [f"T-{i}" for i in reversed(range(1, n + 1))]
    df["year"] = year
    return df[["year", "label", "timestamp", "close", "return"]]

# Gom dữ liệu 10 năm gần nhất
all_data = []
for y in range(datetime.today().year - 10, datetime.today().year):
    df = get_last_sessions_before_sep2(y)
    all_data.append(df)

# Kết quả
final_df = pd.concat(all_data).reset_index(drop=True)

# Pivot để tạo bảng
pivot_table = final_df.pivot(index="year", columns="label", values="close")
returns_table = final_df.pivot(index="year", columns="label", values="return")

print("==== Giá đóng cửa (Close) ====")
print(pivot_table.round(2))

print("\n==== Tỷ suất sinh lời hàng ngày (%) ====")
print(returns_table.round(2))
```

## 4. Thống kê số lượng mã cổ phiếu cắt lên và cắt xuống đường MA20

```python
import pandas as pd
import numpy as np
from FiinQuantX import FiinSession
from datetime import datetime, timedelta

# Bước 1: Login
username='Username'
password='Password'
client = FiinSession(username=username, password=password).login()

# Bước 2: Lấy danh sách cổ phiếu trong VNIndex
tickers = client.TickerList(ticker="VNINDEX")

# Bước 3: Lấy dữ liệu lịch sử 60 ngày
event = client.Fetch_Trading_Data(
    realtime=False,
    tickers=tickers,
    fields=["close", "volume"],
    adjusted=True,
    by="1d",
    period=60,
    lasted=True
)
data = event.get_data()

# In ra latest timestamp
latest_timestamp = data["timestamp"].max()
print(f"=== DỮ LIỆU MỚI NHẤT TỚI NGÀY: {latest_timestamp} ===\n")

# Bước 4: Tính SMA20, SMA50 và lọc tín hiệu
fi = client.FiinIndicator()
cut_down, cut_up, above_ma50_falling, below_ma50_rising = [], [], [], []

for ticker in tickers:
    df = data[data['ticker'] == ticker].copy()
    df.sort_values("timestamp", inplace=True)
    df['sma_20'] = fi.sma(df['close'], window=20)
    df['sma_50'] = fi.sma(df['close'], window=50)

    if len(df) < 51:
        continue

    prev_close = df['close'].iloc[-2]
    curr_close = df['close'].iloc[-1]
    prev_sma20 = df['sma_20'].iloc[-2]
    curr_sma20 = df['sma_20'].iloc[-1]
    curr_sma50 = df['sma_50'].iloc[-1]
    volume = df['volume'].iloc[-1]

    if volume < 100_000:
        continue

    # Điều kiện cắt SMA20
    cut_down_condition = (prev_close > prev_sma20 and curr_close < curr_sma20 and
                          (curr_sma20 - curr_close) / curr_sma20 >= 0.005)
    cut_up_condition = (prev_close < prev_sma20 and curr_close > curr_sma20 and
                        (curr_close - curr_sma20) / curr_sma20 >= 0.005)

    if cut_down_condition:
        cut_down.append((ticker, volume))
    elif cut_up_condition:
        cut_up.append((ticker, volume))

    # Điều kiện giá > SMA50 nhưng đang giảm và cách SMA50 < 2%
    if curr_close > curr_sma50 and curr_close < prev_close and \
       abs(curr_close - curr_sma50) / curr_sma50 < 0.02:
        above_ma50_falling.append((ticker, curr_close, curr_sma50))

    # Điều kiện giá < SMA50 nhưng đang tăng và cách SMA50 < 2%
    if curr_close < curr_sma50 and curr_close > prev_close and \
       abs(curr_close - curr_sma50) / curr_sma50 < 0.02:
        below_ma50_rising.append((ticker, curr_close, curr_sma50))

# Bước 5: Sắp xếp theo volume
cut_down_sorted = sorted(cut_down, key=lambda x: x[1], reverse=True)
cut_up_sorted = sorted(cut_up, key=lambda x: x[1], reverse=True)

# Bước 6: In kết quả
print("=== CỔ PHIẾU CẮT XUỐNG SMA20 (>0.5%) VỚI VOLUME > 100K ===")
print(f"Tổng cộng: {len(cut_down_sorted)} mã")
for ticker, vol in cut_down_sorted:
    print(f"{ticker}: {vol:,}")

print("\n=== CỔ PHIẾU CẮT LÊN SMA20 (>0.5%) VỚI VOLUME > 100K ===")
print(f"Tổng cộng: {len(cut_up_sorted)} mã")
for ticker, vol in cut_up_sorted:
    print(f"{ticker}: {vol:,}")

print("\n=== CỔ PHIẾU GIÁ > SMA50, ĐANG GIẢM VÀ CÁCH MA50 <2% ===")
print(f"Tổng cộng: {len(above_ma50_falling)} mã")
for ticker, price, sma50 in above_ma50_falling:
    print(f"{ticker}: Close={price:.2f}, SMA50={sma50:.2f}, Chênh lệch={(price-sma50)/sma50*100:.2f}%")

print("\n=== CỔ PHIẾU GIÁ < SMA50, ĐANG TĂNG VÀ CÁCH MA50 <2% ===")
print(f"Tổng cộng: {len(below_ma50_rising)} mã")
for ticker, price, sma50 in below_ma50_rising:
    print(f"{ticker}: Close={price:.2f}, SMA50={sma50:.2f}, Chênh lệch={(price-sma50)/sma50*100:.2f}%")
```

## 5. Thống kê giá trị điều chỉnh khi thị trường tăng nóng

```python
import pandas as pd
import numpy as np
from FiinQuantX import FiinSession

# =========================
# 1) Đăng nhập & tham số
# =========================
username='username@fiingroup.vn',
password='password'
client = FiinSession(username=username, password=password).login()   # BẮT BUỘC phải login

# ========= 2) Tham số =========
ticker         = "VNINDEX"
from_date      = "2000-01-01"
timeframe      = "1d"
zigzag_pct     = 5.0     # ngưỡng ZigZag (% đảo chiều)
min_pump_pct   = 30.0    # ngưỡng tăng mạnh tối thiểu (%)

# ========= 3) Lấy dữ liệu =========
ev = client.Fetch_Trading_Data(
    realtime=False,
    tickers=ticker,
    fields=['close'],
    adjusted=True,
    by=timeframe,
    from_date=from_date
)
df = pd.DataFrame(ev.get_data())

# Chuẩn hóa thời gian (timestamp có thể là chuỗi)
df['time'] = pd.to_datetime(df['timestamp'], errors='coerce')
df = df.sort_values('time').dropna(subset=['time', 'close']).reset_index(drop=True)
prices = df['close'].astype(float).values

# ========= 4) Hàm ZigZag vững chắc =========
def zigzag_points_by_pct(price_array: np.ndarray, pct: float):
    """Trả về danh sách pivot: [(idx, price, 'low'/'high'), ...]"""
    if price_array.size == 0:
        return []

    pivots = []
    # Khởi tạo: coi điểm đầu là cả đỉnh & đáy
    last_pivot_idx = 0
    last_pivot_val = price_array[0]
    trend = None  # None/'up'/'down'

    # Tìm swing đầu tiên vượt pct
    for i in range(1, len(price_array)):
        chg = (price_array[i] / last_pivot_val - 1.0) * 100.0
        if trend is None:
            if chg >= pct:
                pivots.append((last_pivot_idx, last_pivot_val, 'low'))
                last_pivot_idx, last_pivot_val = i, price_array[i]
                pivots.append((last_pivot_idx, last_pivot_val, 'high'))
                trend = 'up'
            elif chg <= -pct:
                pivots.append((last_pivot_idx, last_pivot_val, 'high'))
                last_pivot_idx, last_pivot_val = i, price_array[i]
                pivots.append((last_pivot_idx, last_pivot_val, 'low'))
                trend = 'down'
            else:
                # chưa đủ biên độ để xác lập trend
                if price_array[i] > last_pivot_val:
                    last_pivot_idx, last_pivot_val = i, price_array[i]  # dồn làm đỉnh tạm
                if price_array[i] < last_pivot_val:
                    last_pivot_idx, last_pivot_val = i, price_array[i]  # dồn làm đáy tạm
                continue
        else:
            if trend == 'up':
                # cập nhật đỉnh trong xu hướng lên
                if price_array[i] > last_pivot_val:
                    last_pivot_idx, last_pivot_val = i, price_array[i]
                    # cập nhật pivot 'high' cuối danh sách
                    if pivots and pivots[-1][2] == 'high':
                        pivots[-1] = (last_pivot_idx, last_pivot_val, 'high')
                # kiểm tra đảo chiều đủ pct
                drawdown = (price_array[i] / last_pivot_val - 1.0) * 100.0
                if drawdown <= -pct:
                    # chốt đỉnh
                    # (đỉnh đã là pivots[-1])
                    # bắt đầu xu hướng giảm: ghi đáy mới
                    last_pivot_idx, last_pivot_val = i, price_array[i]
                    pivots.append((last_pivot_idx, last_pivot_val, 'low'))
                    trend = 'down'
            else:  # trend == 'down'
                # cập nhật đáy trong xu hướng xuống
                if price_array[i] < last_pivot_val:
                    last_pivot_idx, last_pivot_val = i, price_array[i]
                    # cập nhật pivot 'low' cuối danh sách
                    if pivots and pivots[-1][2] == 'low':
                        pivots[-1] = (last_pivot_idx, last_pivot_val, 'low')
                # kiểm tra đảo chiều đủ pct
                rebound = (price_array[i] / last_pivot_val - 1.0) * 100.0
                if rebound >= pct:
                    # chốt đáy
                    # (đáy đã là pivots[-1])
                    # bắt đầu xu hướng lên: ghi đỉnh mới
                    last_pivot_idx, last_pivot_val = i, price_array[i]
                    pivots.append((last_pivot_idx, last_pivot_val, 'high'))
                    trend = 'up'

    # Lọc trùng chỉ số
    cleaned = []
    seen = set()
    for idx, val, typ in pivots:
        if idx not in seen:
            cleaned.append((idx, val, typ))
            seen.add(idx)
    return cleaned

pivots = zigzag_points_by_pct(prices, pct=zigzag_pct)

# ========= 5) Tạo bảng sự kiện: low -> high (tăng), rồi high -> low (chỉnh) =========
events = []
for i in range(len(pivots) - 2):
    i0, p0, t0 = pivots[i]
    i1, p1, t1 = pivots[i+1]
    i2, p2, t2 = pivots[i+2]
    if t0 == 'low' and t1 == 'high' and t2 == 'low':
        inc_pct = (p1 / p0 - 1.0) * 100.0
        if inc_pct >= min_pump_pct:
            corr_pct = (p2 / p1 - 1.0) * 100.0  # âm là giảm
            events.append({
                "start": df.loc[i0, 'time'],
                "peak":  df.loc[i1, 'time'],
                "end":   df.loc[i2, 'time'],
                "increase_%": round(inc_pct, 2),
                "correction_%": round(corr_pct, 2),
                "days": int((df.loc[i2, 'time'] - df.loc[i1, 'time']).days)
            })

# DataFrame kết quả (tạo cột dù trống để tránh KeyError)
result_cols = ["start", "peak", "end", "increase_%", "correction_%", "days"]
result = pd.DataFrame(events, columns=result_cols).sort_values('peak')

# ========= 6) Thống kê tổng hợp an toàn =========
def safe_stats(rdf: pd.DataFrame):
    if rdf.empty:
        return {
            "Số nhịp tăng >30% quan sát": 0,
            "Mức chỉnh TB (%)": np.nan,
            "Median (%)": np.nan,
            "Mức chỉnh lớn nhất (%)": np.nan,
            "Mức chỉnh nhỏ nhất (%)": np.nan,
            "Số ngày chỉnh TB": np.nan
        }
    return {
        "Số nhịp tăng >30% quan sát": int(len(rdf)),
        "Mức chỉnh TB (%)": round(rdf['correction_%'].mean(), 2),
        "Median (%)": round(rdf['correction_%'].median(), 2),
        "Mức chỉnh lớn nhất (%)": round(rdf['correction_%'].min(), 2),
        "Mức chỉnh nhỏ nhất (%)": round(rdf['correction_%'].max(), 2),
        "Số ngày chỉnh TB": round(rdf['days'].mean(), 1)
    }

summary = safe_stats(result)

# ========= 7) In kết quả =========
print("\n=== BẢNG SỰ KIỆN (VNINDEX) — tăng > %.1f%% rồi chỉnh theo ZigZag %.1f%% ===" % (min_pump_pct, zigzag_pct))
print(result.to_string(index=False))

print("\n=== THỐNG KÊ TỔNG HỢP (VNINDEX) ===")
for k, v in summary.items():
    print(f"{k}: {v}")

# ========= 8) Top 10 nhịp chỉnh mạnh nhất =========
if not result.empty:
    top10 = result.sort_values('correction_%').head(10)  # correction_% âm -> càng nhỏ càng giảm mạnh
    print("\n=== TOP 10 NHỊP CHỈNH MẠNH NHẤT ===")
    print(top10.to_string(index=False))

```


# Mô hình sàng lọc


# Chiến lược đầu tư


# Mô hình AI/ML

## Mô hình AI để phân tích giá cổ phiếu trong lịch sử&#x20;

{% hint style="info" %}
Sử dụng các mô hình LLM với data của FiinQuant để hỗ trợ trong việc tìm ra các insight theo yêu cầu của người dùng
{% endhint %}

```python
import requests
import google.generativeai as genai
import pandas as pd

from FiinQuantX import FiinSession
from bs4 import BeautifulSoup

GOOGLE_GEMINI_API_KEY = 'YOUR_GOOGLE_GEMINI_API_KEY'
genai.configure(api_key=GOOGLE_GEMINI_API_KEY)
model = genai.GenerativeModel("gemini-1.5-flash")


```

```python
username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

VCB_data = client.Fetch_Trading_Data(
    tickers=['VCB'],
    fields=['close'],
    realtime=False,
    adjusted=True,
    by='1d', 
    from_date='2020-01-01',
    to_date='2025-01-29').get_data()
```

```python
prompt = None
prompt = (
    "You are a helpful assistant that can provide meaningful information about the stock market from the data given by the user.\n"
    "The data given by the user is a pandas dataframe with the following columns: 'Ticker', 'Date', 'Close'.\n"
    "You need to provide a summary of the data and the trends of the stock market.\n"
    "You need to find the percentage of the stock price change in the last 10 days.\n"
    "Here is the data:\n"
)
prompt += VCB_data.to_string()
```

```python
response = model.generate_content(prompt)
print(response.text)
```

Output:&#x20;

```markdown
Here's a summary of the provided stock market data for VCB, along with an analysis of trends and the 10-day percentage change:
Data Summary:
The dataset contains daily closing prices ('Close') for VCB stock from January 25, 2021, to January 24, 2025. The data shows significant fluctuations in the stock price over this period.
Trend Analysis:
A visual representation (like a line chart) would provide the clearest picture of the trends, but based on the data, we can infer the following:
Long-Term Trend: There's a general upward trend in the price of VCB from 2021 to 2025. However, there are periods of both significant growth and substantial decline within that long term trend.
Volatility: The stock is demonstrably volatile, experiencing both sharp increases and decreases within short timeframes. Significant price swings are visible throughout the dataset.
Seasonal Effects: A more detailed analysis might reveal seasonal patterns in VCB's price movements, but that is beyond the scope of this basic summary.
10-Day Percentage Change:
To calculate the 10-day percentage change, we need the closing prices for the last 10 days of the dataset. These are:
Day -10: 92900.00
Day -9: 92500.00
Day -8: 93000.00
Day -7: 92500.00
Day -6: 92000.00
Day -5: 91000.00
Day -4: 92000.00
Day -3: 91200.00
Day -2: 91000.00
Day -1: 88500.00
Day 0: 89800.00
The calculation is as follows:
Find the difference: 89800.00 - 92900.00 = -3100.00
Calculate the percentage change: (-3100.00 / 92900.00) * 100% = -3.338%
Therefore, the VCB stock price experienced an approximate -3.34% change over the last 10 days. Note that this calculation uses the simple percentage change. More sophisticated calculations could be used to smooth this value.
Further Analysis:
For a more comprehensive understanding of VCB's performance, additional data analysis is recommended including:
Moving Averages: Calculate moving averages (e.g., 50-day, 200-day) to identify longer-term trends and smoother price movements.
Statistical Measures: Calculate metrics like standard deviation to quantify volatility.
Correlation Analysis: Analyze the correlation of VCB's price with other market indices or relevant economic indicators.
Visualizations: Create charts (line charts, candlestick charts) to visualize trends and patterns.
This expanded analysis would offer a richer picture of the stock's historical performance and potential future behavior.
```

## Mô Hình Machine Learning dự đoán giá cổ phiếu&#x20;

Lấy dữ liệu cổ phiếu từ thư viện Fiinquant

<pre class="language-python"><code class="lang-python">import pandas as pd
import numpy as np

from FiinQuantX import FiinSession
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.ensemble import RandomForestRegressor

username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

<strong>VCB_data = client.Fetch_Trading_Data(
</strong>    tickers='VCB',
    fields=['open','high','low','close','volume'],
    adjusted=True,
    period=10,
    realtime=False,
    by='1m',
).get_data()
</code></pre>

### 1. Linear Regression&#x20;

{% hint style="info" %}
**Linear Regression (Hồi quy tuyến tính)**

* **Ý tưởng chính**: Mô hình dự đoán giá cổ phiếu bằng cách tìm một đường thẳng phù hợp nhất với dữ liệu quá khứ. Công thức tổng quát: y=w0+w1x1+w2x2+...+wnxn+ϵy = w\_0 + w\_1 x\_1 + w\_2 x\_2 + ... + w\_n x\_n + \epsilony=w0​+w1​x1​+w2​x2​+...+wn​xn​+ϵ với yyy là giá cổ phiếu, xix\_ixi​ là các yếu tố ảnh hưởng như giá mở cửa, khối lượng giao dịch,...
* **Ưu điểm**: Đơn giản, dễ hiểu, tính toán nhanh.
* **Nhược điểm**: Giả định mối quan hệ tuyến tính giữa các biến, khó bắt được sự phi tuyến của giá cổ phiếu.
  {% endhint %}

Chuẩn bị dữ liệu và chạy mô hình

```python
# Convert Date column to datetime
VCB_data['Date'] = pd.to_datetime(VCB_data['timestamp'])
VCB_data.set_index('Date', inplace=True)
VCB_data.sort_index(inplace=True)

# Define the window size (360 days) and prepare train and test data
window_size = 360
shift_periods = 30  

# Create a list to store predictions and actual values
predictions = []
actuals = []

# Shift the 'Close' column to create the target variable for the next month
VCB_data['Target'] = VCB_data['close'].shift(-shift_periods)

# Drop rows with NaN values in the 'Target' column
VCB_data.dropna(subset=['Target'], inplace=True)

# Iterate over the dataset with a rolling window
for i in range(window_size, len(VCB_data)):
    train_data = VCB_data.iloc[i-window_size:i]
    test_data = VCB_data.iloc[i:i+1]
    
    X_train = train_data[['open', 'high', 'low', 'volume', 'close']]
    y_train = train_data['Target']
    X_test = test_data[['open', 'high', 'low', 'volume', 'close']]
    y_test = test_data['Target']
    
    # Fit the model
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    # Predict the next month's closing price
    prediction = model.predict(X_test)
    predictions.append(prediction[0])
    actuals.append(y_test.values[0])

# Convert predictions and actuals to numpy arrays for evaluation
predictions = np.array(predictions)
actuals = np.array(actuals)

# Calculate evaluation metrics
rmse = np.sqrt(mean_squared_error(actuals, predictions))

# Evaluation
print("Root Mean Square Error (RMSE):", rmse)

dates = VCB_data.index[window_size:window_size + len(predictions)]

plt.figure(figsize=(14, 7))
plt.plot(dates, actuals, label='Actual', color='b')
plt.plot(dates, predictions, label='Predicted', color='r', linestyle='--')
plt.xlabel('Date')
plt.ylabel('Closing Price')
plt.title('Actual vs Predicted Closing Prices Over Time')
plt.legend()
plt.show()
```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2Fhk83FW2gsrN57lPYhkeN%2FScreenshot%202025-02-14%20at%2010.25.12.png?alt=media&amp;token=b7c65ba6-187b-4d4c-803d-fa1a8be398b5" alt=""><figcaption><p>Mô hình Linear Regression dự đoán so với giá thực tế</p></figcaption></figure>

### 2. Random Forest/ XG Boost

{% hint style="info" %}

* **Ý tưởng chính**: Mô hình sử dụng nhiều cây quyết định (**Decision Trees**) để đưa ra dự đoán trung bình từ các cây đó, giúp giảm overfitting.
* **Ưu điểm**:
  * Không yêu cầu dữ liệu phải có quan hệ tuyến tính.
  * Mạnh mẽ với dữ liệu có nhiều yếu tố tác động.
* **Nhược điểm**:
  * Chậm hơn so với Linear Regression khi dữ liệu lớn.
  * Không tốt trong việc dự đoán chuỗi thời gian do không có khả năng ghi nhớ thông tin quá khứ.
    {% endhint %}

```python
# Convert Date column to datetime
VCB_data['Date'] = pd.to_datetime(VCB_data['timestamp'])
VCB_data.set_index('Date', inplace=True)
VCB_data.sort_index(inplace=True)

# Define the window size (360 days) and prepare train and test data
window_size = 360
shift_periods = 30  

# Create a list to store predictions and actual values
predictions = []
actuals = []

# Shift the 'Close' column to create the target variable for the next month
VCB_data['Target'] = VCB_data['close'].shift(-shift_periods)

# Drop rows with NaN values in the 'Target' column
VCB_data.dropna(subset=['Target'], inplace=True)

# Iterate over the dataset with a rolling window
for i in range(window_size, len(VCB_data)):
    train_data = VCB_data.iloc[i-window_size:i]
    test_data = VCB_data.iloc[i:i+1]
    
    X_train = train_data[['open', 'high', 'low', 'volume', 'close']]
    y_train = train_data['Target']
    X_test = test_data[['open', 'high', 'low', 'volume', 'close']]
    y_test = test_data['Target']
    
    # Fit the model using Random Forest
    model = RandomForestRegressor(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)
    
    # Predict the next month's closing price
    prediction = model.predict(X_test)
    predictions.append(prediction[0])
    actuals.append(y_test.values[0])

# Convert predictions and actuals to numpy arrays for evaluation
predictions = np.array(predictions)
actuals = np.array(actuals)

# Calculate evaluation metrics
rmse = np.sqrt(mean_squared_error(actuals, predictions))

# Evaluation
print("Root Mean Square Error (RMSE):", rmse)

last_30_predictions = predictions[-30:]
last_30_actuals = actuals[-30:]
last_30_dates = VCB_data.index[window_size + len(predictions) - 30:window_size + len(predictions)]

# Plot the last 30 predictions vs the last 30 actuals
plt.figure(figsize=(14, 7))
plt.plot(last_30_dates, last_30_actuals, label='Actual', color='b')
plt.plot(last_30_dates, last_30_predictions, label='Predicted', color='r', linestyle='--')
plt.xlabel('Date')
plt.ylabel('Closing Price')
plt.title('Last 30 Actual vs Predicted Closing Prices')
plt.legend()
plt.show()

```

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FVYC6fIMpszv1gwBG7Z7I%2Fimage.png?alt=media&amp;token=6b748e67-148a-4de7-b391-78bec7c17148" alt=""><figcaption><p>Giá dự đoán so với giá thực tế</p></figcaption></figure>

### 3. Long short-term memory network (LSTM)&#x20;

{% hint style="info" %}

* **Ý tưởng chính**: Là một biến thể của mạng **Recurrent Neural Network (RNN)**, giúp ghi nhớ thông tin trong thời gian dài nhờ cơ chế cổng kiểm soát.
* **Ứng dụng trong dự đoán giá cổ phiếu**: Mô hình có thể học được xu hướng và các mẫu từ dữ liệu giá quá khứ để dự đoán giá tương lai.
* **Ưu điểm**:
  * Tốt trong việc xử lý chuỗi thời gian.
  * Có thể học được xu hướng dài hạn.
* **Nhược điểm**:
  * Yêu cầu dữ liệu lớn để đạt hiệu quả tốt.
  * Độ phức tạp tính toán cao, cần GPU để huấn luyện nhanh.

{% endhint %}

**Mạng LSTM cần thêm features ngoài Open High Low Volume để học được tính chất giá của cổ phiếu**

* **Tạo cột Label chính là giá 'Close' của ngày hôm trước**&#x20;

```python
data['Label'] = data['close'].shift(-1)
```

* Tạo th**êm feature**

<pre class="language-python"><code class="lang-python">def alpha_generate(df):
 # 2. Volume Weighted Average Price (VWAP)
    df['VWAP'] = (df['volume'] * (df['high'] + df['low'] + df['close']) / 3).cumsum() / df['volume'].cumsum()
    df['alpha1'] = (df['high'] * df['low']) ** 0.5 - df['VWAP']
    df['alpha2'] = (df['close'] - df['open']) / ((df['high'] - df['low']) + 0.001)
    df['p3'] = df['close'].shift(3).bfill()
    df['p6'] = df['close'].shift(6).bfill()
    # 3. Relative Strength Index (RSI)
    def calculate_rsi(df, window=9):
        delta = df['close'].diff()
        gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
        loss = (-delta.where(delta &#x3C; 0, 0)).rolling(window=window).mean()
        RS = gain / loss
        df['RSI'] = 100 - (100 / (1 + RS))
        df['RSI'] = df['RSI'].bfill()

    calculate_rsi(df)
    def calculate_ewma(close_prices, alpha):
        return close_prices.ewm(alpha=0.9).mean()

<strong>    def calculate_lagged_return(prices, lag):
</strong>        log_returns = np.log(prices) - np.log(prices).shift(lag)
        return log_returns.bfill()
    
    df['lag_1'] = calculate_lagged_return(df['close'], 1)
    df['lag_2'] = calculate_lagged_return(df['close'], 2)
#TODO: USER NEEDS TO CHOOSE THEIR OWN FEATURE ENGINEERING 
</code></pre>

```python
data = alpha_generate(data)
```

* Chuẩn hoá dữ liệu&#x20;

```python
data = data.set_index('date')
close_max = data['close'].max()
close_min = data['close'].min()
data.drop(['stt', 'ticker', 'name'], axis=1, inplace=True)
columns = data.columns
scaler = MinMaxScaler()
data = pd.DataFrame(scaler.fit_transform(data), columns=columns, index=data.index)
data
```

* **Model**&#x20;

```python
class LSTMModel(nn.Module):
    def __init__(self, d_feat=6, hidden_size=64, num_layers=2, dropout=0.0):
        super().__init__()

        self.rnn = nn.LSTM(
            input_size=d_feat,
            hidden_size=hidden_size,
            num_layers=num_layers,
            batch_first=True,
            dropout=dropout,
        )
        self.fc_out = nn.Linear(hidden_size, 1)

        self.d_feat = d_feat

    def forward(self, x):
        # x: [N, F*T]
        x = x.reshape(len(x), self.d_feat, -1)  # [N, F, T]
        x = x.permute(0, 2, 1)  # [N, T, F]
        out, _ = self.rnn(x)
        return self.fc_out(out[:, -1, :]).squeeze()
d_feat = 6
hidden_size = 128
num_layers = 2
dropout = 0.05
n_epochs = 1000
lr = 0.00001
batch_size=7
early_stop=1000
loss="mse"
optimizer="adam"
GPU=0

device = torch.device('mps') if torch.backends.mps.is_available() else 'cpu'
device

lstm_model = LSTMModel(
    d_feat=d_feat,
    hidden_size=hidden_size,
    num_layers=num_layers,
    dropout=dropout,
)
lstm_model = lstm_model.to(device)

def loss_fn(pred, label):
    mask = ~torch.isnan(label)
    loss = (pred[mask] - label[mask]) ** 2
    return torch.mean(loss)

if optimizer.lower() == "adam":
    train_optimizer = optim.Adam(lstm_model.parameters(), lr=lr)
if optimizer.lower() == "gd":
    train_optimizer = optim.SGD(lstm_model.parameters(), lr=lr)
```

.....

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FQqXPrXwnbauLt3JkbJWq%2Fimage.png?alt=media&amp;token=61032c9c-dec8-44fa-ae63-cb441d0d3a06" alt=""><figcaption></figcaption></figure>


# Các mô hình khác

{% embed url="<https://datawrapper.dwcdn.net/c5p5y/1/>" %}

{% embed url="<https://public.tableau.com/views/OIWAP/Dashboard1?:display_count=n&:language=en-US&:origin=viz_share_link&:redirect=auth&:sid=&publish=yes>" %}


# Phân tích phái sinh

Ứng dụng tính số điểm tăng/giảm ở các nến và thống kê khi nến 15 phút tăng trên 10 điểm:

```python
import pandas as pd

from FiinQuantX import FiinSession

# Đăng nhập
username = 'REPLACE_WITH_YOUR_USER_NAME'
password = 'REPLACE_WITH_YOUR_PASS_WORD'

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

# Lấy dữ liệu nến 15 phút của VN30F1M
event = client.Fetch_Trading_Data(
    realtime=False,
    tickers=["VN30F1M"],
    fields=["open", "close", "volume"],
    adjusted=True,
    by="15m",
    period=1000
)
 
df = event.get_data()
 
# Tính chênh lệch giá và volume trung bình 5 nến
df["diff"] = df["close"] - df["open"]
df["vol_avg_5"] = df["volume"].rolling(window=5).mean()
 
# Lọc nến tăng > 10 điểm
signal_bars = df[df["diff"] > 10].copy()
 
# Tính tỷ lệ volume so với trung bình
signal_bars["vol_ratio"] = signal_bars["volume"] / signal_bars["vol_avg_5"]
 
# Tính số điểm tăng/giảm ở các nến kế tiếp
results = []
for idx in signal_bars.index:
    try:
        base_price = df.loc[idx]["close"]
        point_changes = [
            df.loc[idx+1]["close"] - base_price,
            df.loc[idx+2]["close"] - base_price,
            df.loc[idx+3]["close"] - base_price,
        ]
    except:
        point_changes = [None, None, None]
    results.append(point_changes)
 
signal_bars[["n+1_pts", "n+2_pts", "n+3_pts"]] = pd.DataFrame(results, index=signal_bars.index)
 
# In kết quả chi tiết
print(signal_bars[["timestamp", "open", "close", "diff", "volume", "vol_ratio", "n+1_pts", "n+2_pts", "n+3_pts"]])
 
# Thống kê
print("\n📊 Thống kê khi nến 15' tăng > 10 điểm:")
print(f"Tổng số nến tín hiệu: {len(signal_bars)}")
print(f" - N+1 trung bình: {signal_bars['n+1_pts'].mean():.2f} điểm")
print(f" - N+2 trung bình: {signal_bars['n+2_pts'].mean():.2f} điểm")
print(f" - N+3 trung bình: {signal_bars['n+3_pts'].mean():.2f} điểm")
print(f" - Tỷ lệ volume TB (vol_ratio): {signal_bars['vol_ratio'].mean():.2f} lần")
```

Kết quả trả ra

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2Fs3NiZSnEkUvsiV3N4s7Y%2Fimage.png?alt=media&amp;token=6af33ec0-4c9b-4805-a856-1de3b1eb3667" alt=""><figcaption></figcaption></figure>


# Cấu trúc dữ liệu mẫu


# Mẫu dữ liệu BCTC hợp nhất

* Loại hình doanh nghiệp: CTCK, NH, BH, CTY
* Doanh nghiệp mẫu: HPG, SSI, VCB, BVH

List các dictionary, trong đó mỗi dictionary sẽ tương ứng với data của 1 kỳ báo cáo, dưới đây là mô tả&#x20;

## <mark style="color:purple;">1. Bảng cân đối kế toán</mark>

### 1.1. Doanh nghiệp sản xuất

```json
[	
    {	
        "ticker": "HPG",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "balanceSheet": [	
                {	
                    "assets": {	
                        "totalAssets": 224489707553981,	
                        "currentAssets": {	
                            "shortTermInvestments": {	
                                "totalShortTermInvestments": 18974716730905,     	
                                "tradingSecurities": 0,	
                                "heldToMaturityInvestments": 18974716730905,     	
                                "provisionForTradingSecurities": 0	
                            },	
                            "shortTermReceivables": {	
                                "tradeReceivables": 4352135419872,	
                                "shortTermInternalReceivables": 0,	
                                "receivablesUnderConstructionContracts": 0,      	
                                "advancesToSuppliers": 2118824427004,	
                                "allowanceForDoubtfulReceivables": -159993736285,	
                                "pendingAssetsShortage": 379714580,	
                                "shortTermLoans": 87461616439,	
                                "otherReceivables": 1248992845378,	
                                "totalShortTermReceivables": 7647800286988       	
                            },	
                            "inventories": {	
                                "allowanceForImpairment": -101069892341,	
                                "inventories": 46192292081813,	
                                "totalInventories": 46091222189472	
                            },	
                            "totalCurrentAssets": 86674276272995,	
                            "cashAndCashEquivalents": {	
                                "totalCashAndCashEquivalents": 6887646139852,    	
                                "cashEquivalents": 3968114193944,	
                                "cash": 2919531945908	
                            },	
                            "otherCurrentAssets": {	
                                "taxAndOrderReceivables": 10074967536,	
                                "other": 0,	
                                "governmentBondRepurchaseAgreement": 0,	
                                "prepayments": 426149499088,	
                                "totalOtherCurrentAssets": 7072890925778,        	
                                "deductibleValueAddedTax": 6636666459154	
                            }	
                        },	
                        "longTermAssets": {	
                            "otherLongTermAssets": {	
                                "other": 0,	
                                "deferredTaxAssets": 254671208385,	
                                "prepayments": 4269141694868,	
                                "longTermSparePartsAndEquipment": 429422385383,	
                                "totalOtherLongTermAssets": 5016848415359,	
                                "goodWill": 63613126723	
                            },	
                            "totalLongTermAssets": 137815431280986,	
                            "longTermAssetsInProgress": {	
                                "constructionInProgress": 63655857440382,	
                                "totalLongTermAssetsInProgress": 63750717325406,	
                                "longTermWorkInProgress": 94859885024	
                            },	
                            "longTermInvestments": {	
                                "provisionForLongTermInvestments": 0,	
                                "heldToMaturityInvestments": 136500000000,	
                                "totalLongTermInvestments": 136500000000,	
                                "equityInvestmentsInOthers": 0,	
                                "investmentsInSubsidiaries": 0,	
                                "investmentsInJointVentures": 0	
                            },	
                            "fixedAssets": {	
                                "intangibleAssets": {	
                                    "cost": 367057604707,	
                                    "accumulatedAmortisation": -182841626241,	
                                    "totalIntangibleAssets": 184215978466	
                                },	
                                "financeLeaseFixedAssets": {	
                                    "cost": 0,	
                                    "totalFinanceLeaseFixedAssets": 0,	
                                    "accumulatedDepreciation": 0	
                                },	
                                "totalFixedAssets": 67428366953514,	
                                "tangibleFixedAssets": {	
                                    "cost": 108146566348954,	
                                    "totalTangibleFixedAssets": 67244150975048,	
                                    "accumulatedDepreciation": -40902415373906	
                                }	
                            },	
                            "longTermReceivables": {	
                                "longTermCustomerReceivables": 0,	
                                "longTermAdvancesToSuppliers": 82805287792,	
                                "capitalAtAffiliatedUnits": 0,	
                                "otherLongTermReceivables": 840594835822,	
                                "provisionForDoubtfulLongTermReceivables": 0,	
                                "longTermIntercompanyReceivables": 0,	
                                "longTermLoanReceivables": 0,	
                                "totalLongTermReceivables": 923400123614	
                            },	
                            "investmentProperty": {	
                                "cost": 860549015615,	
                                "accumulatedDepreciation": -300950552522,	
                                "totalInvestmentProperty": 559598463093	
                            }	
                        }	
                    },	
                    "resources": {	
                        "totalResources": 224489707553981,	
                        "liabilities": {	
                            "currentLiabilities": {	
                                "otherPayables": 188076845190,	
                                "shortTermPayableExpenses": 682112072502,	
                                "advancesFromCustomers": 739178306553,	
                                "bonusAndWelfareFund": 1027310381825,	
                                "totalCurrentLiabilities": 75225243262689,	
                                "shortTermUnearnedRevenue": 11060479431,	
                                "accountsPayableToSuppliers": 14046841160127,	
                                "payableToEmployees": 890893543298,	
                                "governmentBondRepurchaseTransactions": 0,	
                                "borrowings": 55882686213459,	
                                "priceStabilizationFund": 0,	
                                "shortTermInternalPayables": 0,	
                                "shortTermProvisionForPayables": 13672830889,	
                                "taxPayables": 1743411429415,	
                                "constructionContractPayablesByProgress": 0	
                            },	
                            "totalLiabilities": 109842249570282,	
                            "longTermLiabilities": {	
                                "internalCapitalContributionPayables": 0,	
                                "longTermUnearnedRevenue": 0,	
                                "preferredShares": 0,	
                                "deferredTaxLiabilities": 29268483140,	
                                "scienceAndTechnologyDevelopmentFund": 0,	
                                "convertibleBonds": 0,	
                                "longTermAccusedExpenses": 1143692237207,	
                                "longTermProvisionForPayables": 67495546940,	
                                "longTermInternalPayables": 0,	
                                "otherLongTermPayables": 12476505170,	
                                "borrowings": 27080443256096,	
                                "totalLongTermLiabilities": 34617006307593,	
                                "longTermTradePayables": 6283630279040,	
                                "longTermAdvancesFromCustomers": 0	
                            }	
                        },	
                        "equity": {	
                            "ownersEquity": {	
                                "convertibleBondOptions": 0,	
                                "preferredShares": 0,	
                                "totalOwnersEquity": 114647457983699,	
                                "treasuryShares": 0,	
                                "foreignExchangeDifferences": 0,	
                                "otherOwnersCapital": 0,	
                                "reorganizationSupportFund": 0,	
                                "nonControllingInterests": 290990632368,	
                                "sharePremium": 0,	
                                "shareCapital": 63962502000000,	
                                "assetRevaluationSurplus": 0,	
                                "developmentInvestmentFund": 794841242128,	
                                "constructionInvestmentCapital": 0,	
                                "otherEquityFunds": 0,	
                                "retainedEarnings": {	
                                    "retainedEarningsCurrent": 11974873561074,	
                                    "retainedEarningsPrevious": 37624250548129,	
                                    "totalRetainedEarnings": 49599124109203	
                                }	
                            },	
                            "totalEquity": 114647457983699,	
                            "fundsAndOtherSources": {	
                                "fixedAssetFunding": 0,	
                                "totalOtherFunds": 0,	
                                "fundingSources": 0	
                            }	
                        }	
                    }	
                }	
            ]	
        },	
        "companyType": "MANUFACTURING",	
        "businessTypeId": 3	
    }	
]	
```

### 1.2. Ngân hàng&#x20;

```json
[	
    {	
        "ticker": "VCB",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "balanceSheet": [	
                {	
                    "assets": {	
                        "derivativesAndOtherFinancialAssets": 1314434000000,	
                        "otherAssets": {	
                            "goodwill": 0,	
                            "other": 6516040000000,	
                            "totalOtherAssets": 30402348000000,	
                            "deferredTaxAssets": 991748000000,	
                            "receivables": 14040294000000,	
                            "accruedInterestAndFeeReceivables": 8868303000000,	
                            "allowanceForLosses": -14037000000	
                        },	
                        "totalAssets": 2085873522000000,	
                        "loansToCustomers": {	
                            "loansToCustomers": 1449198899000000,	
                            "totalLoansToCustomers": 1418015724000000,	
                            "allowanceForCreditLosses": -31183175000000	
                        },	
                        "cashOnHandGoldAndGemstones": 14268064000000,	
                        "balancesWithTheStateBankOfVietnam": 49340493000000,	
                        "heldForTradingSecurities": {	
                            "totalHeldForTradingSecurities": 4876237000000,	
                            "heldForTradingSecurities": 4908527000000,	
                            "allowanceForLossesOnHeldForTradingSecurities": -32290000000	
                        },	
                        "investmentSecurities": {	
                            "availableForSaleSecurities": 86799901000000,	
                            "heldToMaturitySecurities": 80829540000000,	
                            "totalInvestmentSecurities": 167383349000000,	
                            "allowanceForLossesOnInvestmentSecurities": -246092000000   	
                        },	
                        "fixedAssets": {	
                            "intangibleAssets": {	
                                "cost": 5072735000000,	
                                "accumulatedAmortisation": -2510437000000,	
                                "totalIntangibleAssets": 2562298000000	
                            },	
                            "financeLeaseFixedAssets": {	
                                "cost": 0,	
                                "totalFinanceLeaseFixedAssets": 0,	
                                "accumulatedDepreciation": 0	
                            },	
                            "totalFixedAssets": 8092877000000,	
                            "tangibleFixedAssets": {	
                                "cost": 15808302000000,	
                                "totalTangibleFixedAssets": 5530579000000,	
                                "accumulatedDepreciation": -10277723000000	
                            }	
                        },	
                        "longTermInvestment": {	
                            "otherLongTermInvestments": 1528922000000,	
                            "investmentsInJointVenture": 763736000000,	
                            "provisionForLongTermInvestments": -75000000000,	
                            "investmentInSubsidiaries": 0,	
                            "investmentsInAssociates": 10440000000,	
                            "totalLongTermInvestment": 2228098000000	
                        },	
                        "debtPurchases": {	
                            "allowanceForDebtPurchases": 0,	
                            "debtPurchases": 0	
                        },	
                        "depositsWithAndLoansToOtherCreditInstitutions": {	
                            "totalDepositsWithAndLoansToOtherCreditInstitutions": 389951898000000,	
                            "depositsWithOtherInstitutions": 384031890000000,	
                            "allowanceForCreditLosses": -1000000000000,	
                            "loansToOtherInstitutions": 6920008000000	
                        },	
                        "investmentProperty": {	
                            "cost": 0,	
                            "accumulatedDepreciation": 0,	
                            "totalInvestmentProperty": 0	
                        }	
                    },	
                    "resources": {	
                        "totalResources": 2085873522000000,	
                        "liabilities": {	
                            "fundsAndEntrustedInvestmentsReceivedFromTheGovernmentInternationalAndOtherCreditInstitutions": 529000000,	
                            "depositsFromCustomers": 1514664850000000,	
                            "otherLiabilities": {	
                                "other": 24112345000000,	
                                "accruedInterestPayable": 13990276000000,	
                                "totalOtherLiabilities": 38102621000000,	
                                "taxPayables": 0,	
                                "allowanceForLosses": 0	
                            },	
                            "derivativesAndOtherFinancialLiabilities": 0,	
                            "valuablePapersIssued": 24125059000000,	
                            "totalLiabilities": 1889664354000000,	
                            "dueToTheGovernmentAndTheStateBankOfVietnam": 78237337000000,	
                            "depositsAndBorrowings": {	
                                "borrowingsFromOtherInstitutions": 11362577000000,	
                                "depositsFromOtherInstitutions": 223171381000000,	
                                "depositsAndBorrowingsFromOtherInstitutions": 234533958000000	
                            }	
                        },	
                        "equity": {	
                            "totalEquity": 196209168000000,	
                            "capital": {	
                                "totalCapital": 61696139000000,	
                                "preferredShares": 0,	
                                "charterCapital": 55890913000000,	
                                "treasuryShares": 0,	
                                "sharePremium": 4995389000000,	
                                "ownersOtherCapital": 809837000000	
                            },	
                            "retainedProfits": {	
                                "totalRetainedProfits": 98332086000000	
                            },	
                            "reserves": 37052974000000,	
                            "nonControllingInterests": 96261000000,	
                            "revaluationSurplus": 0,	
                            "exchangeRateDifferences": -968292000000	
                        }	
                    }	
                }	
            ]	
        },	
        "companyType": "BANKING",	
        "businessTypeId": 1	
    }	
]	
```

### 1.3. Doanh nghiệp chứng khoán

```json
[	
    {	
        "ticker": "SSI",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "balanceSheet": [	
                {	
                    "assets": {	
                        "totalAssets": 73507302559722,	
                        "currentAssets": {	
                            "totalCurrentAssets": 70932391912367,	
                            "financialAssets": {	
                                "loans": 21998601885375,	
                                "totalFinancialAssets": 70813502224578,	
                                "provisionForImpairmentOfReceivables": -232039957803,	
                                "otherReceivables": 210104950765,	
                                "availableForSaleFinancialAssets": 562332851822,	
                                "provisionForImpairmentOfFinancialAssetsAndMortgageAssets": -55101823874,     	
                                "receivablesFromServicesProvidedByCompany": 30201748046,	
                                "financialAssetsAtFairValueThroughProfitOrLoss": 42438121481401,	
                                "receivables": {	
                                    "receivablesAndAccrualsFromDividendInterestIncome": {	
                                        "totalReceivablesAndAccrualsFromDividendInterestIncome": 292847293114,	
                                        "dueOrOverdueReceivablesDividendInterest": 0,	
                                        "accrualsForUndueDividendAndInterestIncome": 292847293114	
                                    },	
                                    "totalReceivables": 800614271922,	
                                    "receivablesFromDisposalOfFinancialAssets": 507766978808	
                                },	
                                "receivablesFromSecuritiesTransactionErrors": 0,	
                                "heldToMaturityInvestments": 3893901724895,	
                                "advancesToSuppliers": 927764853829,	
                                "cashAndCashEquivalents": {	
                                    "totalCashAndCashEquivalents": 239000238200,	
                                    "cashEquivalents": 30030246575,	
                                    "cash": 208969991625	
                                },	
                                "internalReceivables": 0	
                            },	
                            "otherCurrentAssets": {	
                                "shortTermDepositsCollateralsAndPledges": 772112130,	
                                "taxesAndStateReceivables": 55944865,	
                                "governmentBondRepurchaseTransactions": 0,	
                                "advances": 20927597892,	
                                "provisionForImpairmentOfOtherCurrentAssets": 0,	
                                "totalOtherCurrentAssets": 118889687789,	
                                "shortTermPrepaidExpenses": 54860667972,	
                                "otherCurrentAssetsDetails": 41677606235,	
                                "deductibleValueAddedTax": 0,	
                                "officeSuppliesToolsAndMaterials": 595758695	
                            }	
                        },	
                        "longTermAssets": {	
                            "totalLongTermAssets": 2574910647355,	
                            "otherLongTermAssets": {	
                                "deferredIncomeTaxAssets": 24001105881,	
                                "longTermDepositsCollateralsAndPledges": 31205273582,	
                                "longTermPrepaidExpenses": 21614788489,	
                                "paymentForSettlementAssistanceFund": 20000000000,	
                                "otherLongTermAssetsDetails": 33312364248,	
                                "totalOtherLongTermAssets": 130133532200,	
                                "longTermEquipmentMaterialAndSpareParts": 0,	
                                "goodWill": 0	
                            },	
                            "constructionInProgress": 387623333376,	
                            "provisionForImpairmentOfLongTermAssets": 0,	
                            "investmentProperties": {	
                                "revaluationOfFixedAssetsInFinancialLeaseUsingFairValueModel": 0,	
                                "cost": 287459600028,	
                                "totalInvestmentProperties": 200196436698,	
                                "accumulatedDepreciation": -87263163330	
                            },	
                            "longTermFinancialAssets": {	
                                "totalLongTermFinancialAssets": 1625606669387,	
                                "longTermInvestments": {	
                                    "otherLongTermInvestments": 0,	
                                    "investmentInJointVenturesAndAssociates": 687490406131,	
                                    "investmentInSubsidiaries": 0,	
                                    "totalLongTermInvestments": 1625606669387,	
                                    "heldToMaturityInvestments": 938116263256	
                                },	
                                "provisionForImpairmentOfLongTermInvestments": 0,	
                                "longTermReceivables": 0	
                            },	
                            "fixedAssets": {	
                                "intangibleFixedAssets": {	
                                    "revaluationOfFixedAssetsInFinancialLeaseUsingFairValueModel": 0,	
                                    "cost": 313999554731,	
                                    "accumulatedAmortisation": -201155598936,	
                                    "totalIntangibleAssets": 112843955795	
                                },	
                                "financeLeaseFixedAssets": {	
                                    "cost": 0,	
                                    "totalFinanceLeaseFixedAssets": 0,	
                                    "accumulatedDepreciation": 0	
                                },	
                                "totalFixedAssets": 231350675694,	
                                "tangibleFixedAssets": {	
                                    "cost": 408360121790,	
                                    "totalTangibleFixedAssets": 118506719899,	
                                    "accumulatedDepreciation": -289853401891	
                                }	
                            }	
                        }	
                    },	
                    "resources": {	
                        "totalResources": 73507302559722,	
                        "fundingSourcesAndOtherFunds": 0,	
                        "liabilities": {	
                            "currentLiabilities": {	
                                "shortTermDepositsAndCollateralReceived": 362313180,	
                                "otherShortTermPayables": 18037472054,	
                                "payablesToEmployees": 93761808205,	
                                "convertibleBondsShortTerm": 0,	
                                "totalCurrentLiabilities": 46599438522989,	
                                "shortTermFinanceLeasePayables": 0,	
                                "bonusAndWelfareFund": 356533362422,	
                                "paymentSupportFund": 0,	
                                "issuedBondsShortTerm": 0,	
                                "shortTermUnearnedRevenue": 1299798330,	
                                "shortTermAccruedExpenses": 67847177428,	
                                "bondsRepurchaseTransactions": 0,	
                                "constructionContractInProgressPayables": 0,	
                                "payablesDueToFinancialAssetErrors": 0,	
                                "shortTermTradePayables": 103075387679,	
                                "shortTermAdvanceFromCustomers": 26490726300,	
                                "provisionForShortTermLiabilities": 0,	
                                "payablesFromSecuritiesTransactions": 227883634106,	
                                "shortTermInternalPayables": 0,	
                                "shortTermBorrowingsAndFinancialLeases": {	
                                    "totalShortTermBorrowingsAndFinancialLeases": 45501969699137,	
                                    "shortTermBorrowings": 45501969699137,	
                                    "shortTermFinanceLeaseLiabilities": 0	
                                },	
                                "employeeBenefits": 884019653,	
                                "statutoryObligation": 201293124495	
                            },	
                            "totalLiabilities": 46680651947954,	
                            "longTermLiabilities": {	
                                "issuedBondsLongTerm": 0,	
                                "deferredIncomeTaxPayable": 26650541290,	
                                "provisionForInvestorCompensation": 0,	
                                "longTermFinanceLeasePayables": 0,	
                                "longTermUnearnedRevenue": 54562883675,	
                                "longTermAccruedExpenses": 0,	
                                "scienceAndTechnologyDevelopmentFund": 0,	
                                "convertibleBonds": 0,	
                                "longTermBorrowingsAndFinancialLeases": {	
                                    "totalLongTermBorrowingsAndFinancialLeases": 0,	
                                    "longTermFinanceLeaseLiabilities": 0,	
                                    "longTermBorrowings": 0	
                                },	
                                "longTermInternalPayables": 0,	
                                "longTermCollateralsReceived": 0,	
                                "otherLongTermPayables": 0,	
                                "totalLongTermLiabilities": 81213424965,	
                                "provisionForLongTermLiabilities": 0,	
                                "longTermTradePayables": 0,	
                                "longTermAdvanceFromCustomers": 0	
                            }	
                        },	
                        "equity": {	
                            "ownersEquity": {	
                                "shareCapital": {	
                                    "otherOwnerCapital": 0,	
                                    "totalShareCapital": 20713065094108,	
                                    "capitalContribution": {	
                                        "ordinaryShares": 19638639180000,	
                                        "preferredShares": 0,	
                                        "totalCapitalContribution": 19638639180000	
                                    },	
                                    "convertibleBondOption": 0,	
                                    "treasuryShares": -19115006409,	
                                    "sharePremium": 1093540920517	
                                },	
                                "totalOwnersEquity": 26826650611768,	
                                "differencesFromRevaluationOfAssetsAtFairValue": 31690477740,	
                                "undistributedProfit": {	
                                    "realizedProfit": 6025186849191,	
                                    "totalUndistributedProfit": 5856098315938,	
                                    "unrealizedProfit": -169088533253	
                                },	
                                "ownerFundsReserve": {	
                                    "charterCapitalSupplementaryReserve": 3000000000,	
                                    "otherOwnerFunds": 0	
                                },	
                                "ForeignExchangeRateDifferences": 72177590546,	
                                "nonControllingInterests": 150619133436	
                            },	
                            "totalEquity": 26826650611768	
                        }	
                    }	
                }	
            ]	
        },	
        "companyType": "SECURITIES",	
        "businessTypeId": 3	
    }	
]	
```

### 1.4. Doanh nghiệp bảo hiểm

```json
[	
    {	
        "ticker": "BVH",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "balanceSheet": [	
                {	
                    "assets": {	
                        "totalAssets": 251286326838124,	
                        "currentAssets": {	
                            "reinsuranceAssets": {	
                                "reinsuranceCededClaimsReserve": 1871236613709,	
                                "reinsuranceCededUnearnedPremiumReserve": 1686897782968,  	
                                "totalReinsuranceAssets": 3558134396677	
                            },	
                            "shortTermInvestments": {	
                                "totalShortTermInvestments": 103898039030526,	
                                "tradingSecurities": 3660368511864,	
                                "heldToMaturityInvestments": 100440649810502,	
                                "provisionForTradingSecurities": -202979291840	
                            },	
                            "shortTermReceivables": {	
                                "receivablesFromCustomers": {	
                                    "fromInsuranceActivities": 1265479668075,	
                                    "totalReceivablesFromCustomers": 7892192217650,       	
                                    "otherReceivables": 6626712549575	
                                },	
                                "otherShortTermReceivables": 311080060298,	
                                "shortTermLoansReceivables": 3547995002349,	
                                "provisionForDoubtfulShortTermReceivables": -247913748321,	
                                "advancesToSuppliers": 32063030043,	
                                "totalShortTermReceivables": 11535416562019,	
                                "internalReceivables": 0	
                            },	
                            "inventories": {	
                                "inventories": 100479759917,	
                                "totalInventories": 100479759917,	
                                "provisionForInventoryDevaluation": 0	
                            },	
                            "totalCurrentAssets": 121226741291519,	
                            "cashAndCashEquivalents": {	
                                "totalCashAndCashEquivalents": 1464088127113,	
                                "cashEquivalents": 190000000000,	
                                "cash": 1274088127113	
                            },	
                            "otherCurrentAssets": {	
                                "deductibleVAT": 36415365,	
                                "taxesAndStateReceivables": 4809122226,	
                                "other": 5199723492,	
                                "governmentBondRepurchaseTransactions": 0,	
                                "prepaidExpenses": {	
                                    "totalPrepaidExpenses": 660538154184,	
                                    "unallocatedCommissionExpenses": 581867688103,	
                                    "otherPrepaidExpenses": 78670466081	
                                },	
                                "totalOtherCurrentAssets": 670583415267	
                            }	
                        },	
                        "longTermAssets": {	
                            "totalLongTermAssets": 130059585546605,	
                            "otherLongTermAssets": {	
                                "goodwill": 0,	
                                "other": 26098348989,	
                                "deferredTaxAssets": 7855743207,	
                                "prepayments": 181047015237,	
                                "totalOtherLongTermAssets": 215001107433	
                            },	
                            "investmentProperties": {	
                                "cost": 191327232874,	
                                "totalInvestmentProperties": 109961268939,	
                                "accumulatedDepreciation": -81365963935	
                            },	
                            "longTermAssetsInProgress": {	
                                "totalLongTermAssetsInProgress": 131645367989,	
                                "longTermAssetsInProgress": 131645367989,	
                                "longTermWorkInProgressCosts": 0	
                            },	
                            "longTermInvestments": {	
                                "investmentsInOtherEntities": 1279365243151,	
                                "provisionForLongTermFinancialInvestments": -62506533483,	
                                "totalLongTermInvestments": 127645423169640,	
                                "heldToMaturityInvestments": 123543648618749,	
                                "investmentsInSubsidiaries": 0,	
                                "investmentsInJointVenturesAndAssociates": 2884915841223	
                            },	
                            "fixedAssets": {	
                                "intangibleAssets": {	
                                    "cost": 1840590207970,	
                                    "accumulatedAmortisation": -822369186322,	
                                    "totalIntangibleAssets": 1018221021648	
                                },	
                                "financeLeaseFixedAssets": {	
                                    "cost": 0,	
                                    "totalFinanceLeaseFixedAssets": 0,	
                                    "accumulatedDepreciation": 0	
                                },	
                                "totalFixedAssets": 1890638249670,	
                                "tangibleFixedAssets": {	
                                    "cost": 2726029379554,	
                                    "totalTangibleFixedAssets": 872417228022,	
                                    "accumulatedDepreciation": -1853612151532	
                                }	
                            },	
                            "longTermReceivables": {	
                                "longTermReceivablesFromCustomers": 0,	
                                "internalLongTermReceivables": 0,	
                                "otherLongTermReceivables": {	
                                    "otherLongTermReceivables": 0,	
                                    "totalOtherLongTermReceivables": 66916382934,	
                                    "insuranceDeposits": 66916382934	
                                },	
                                "provisionForDoubtfulLongTermReceivables": 0,	
                                "capitalInAffiliatedUnits": 0,	
                                "totalLongTermReceivables": 66916382934	
                            }	
                        }	
                    },	
                    "resources": {	
                        "totalResources": 251286326838124,	
                        "liabilities": {	
                            "currentLiabilities": {	
                                "otherShortTermPayables": 395628174229,	
                                "payablesToEmployees": 1702090155645,	
                                "taxesAndPayablesToState": 211453081628,	
                                "totalCurrentLiabilities": 40840468409215,	
                                "bonusAndWelfareFund": 0,	
                                "shortTermAccruedExpenses": 141601337253,	
                                "shortTermBorrowingsAndFinanceLeases": 2910226356811,	
                                "governmentBondRepurchaseTransactions": 32123608859706,	
                                "internalPayables": 0,	
                                "shortTermTradePayables": {	
                                    "insuranceOperationPayables": 2370393614148,	
                                    "tradeAndServicePayables": 63568872587,	
                                    "totalShortTermTradePayables": 2433962486735	
                                },	
                                "unearnedCommissionIncome": 382055501051,	
                                "provisionForShortTermLiabilities": 0,	
                                "priceStabilizationFund": 260153881426,	
                                "unearnedRevenue": 258502574731,	
                                "shortTermAdvancesFromCustomers": 21186000000	
                            },	
                            "totalLiabilities": 227720439778201,	
                            "longTermLiabilities": {	
                                "deferredIncomeTaxPayable": 2731324749,	
                                "longTermInternalPayables": 0,	
                                "longTermUnearnedRevenue": 0,	
                                "otherLongTermPayables": 303139567653,	
                                "longTermBorrowings": 0,	
                                "totalLongTermLiabilities": 186879971368986,	
                                "provisionForLongTermLiabilities": 0,	
                                "longTermTradePayables": 0,	
                                "scienceAndTechnologyDevelopmentFund": 0,	
                                "insuranceBusinessProvision": {	
                                    "catastropheProvision": 186907656143,	
                                    "interestRateCommitmentProvision": 16741736693139,	
                                    "other": 0,	
                                    "resilienceProvision": 0,	
                                    "totalInsuranceBusinessProvision": 186574100476584,	
                                    "mathematicalProvision": 5451808363226,	
                                    "equalizationProvision": 412275456267,	
                                    "unearnedPremiumProvision": 157148585024401,	
                                    "dividendProvision": 3521002598958,	
                                    "claimsProvision": 3111784684450	
                                },	
                                "longTermDepositAndMortgage": 0	
                            }	
                        },	
                        "equity": {	
                            "ownersEquity": {	
                                "preferredShares": 0,	
                                "totalOwnersEquity": 23565887059923,	
                                "treasuryShares": 0,	
                                "foreignExchangeDifferences": 15445192000,	
                                "otherOwnersCapital": 0,	
                                "reorganizationSupportFund": 0,	
                                "nonControllingInterests": 974335175004,	
                                "sharePremium": 7310458742807,	
                                "shareCapital": {	
                                    "totalShareCapital": 7423227640000,	
                                    "paidInCapital": 7423227640000	
                                },	
                                "assetRevaluationSurplus": 0,	
                                "developmentInvestmentFund": 2933853033569,	
                                "otherEquityFunds": 103568802818,	
                                "retainedEarnings": {	
                                    "retainedEarningsCurrent": 2007200429930,	
                                    "totalRetainedEarnings": 4007066089089,	
                                    "retainedEarningsPrevious": 1999865659159	
                                }	
                            },	
                            "totalEquity": 23565887059923,	
                            "provisionStatutory": 797932384636	
                        }	
                    }	
                }	
            ]	
        },	
        "companyType": "INSURANCE",	
        "businessTypeId": 1	
    }	
]	
```

## <mark style="color:purple;">2. Báo cáo kết quả hoạt động kinh doanh</mark>&#x20;

### 2.1. Doanh nghiệp sản xuất

```
[	
    {	
        "ticker": "HPG",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "incomeStatement": [	
                {	
                    "earningsPerShare": {	
                        "epsDiluted": 0,	
                        "epsBasic": 0	
                    },	
                    "taxExpenses": {	
                        "currentIncomeTaxExpense": -503217741562,        	
                        "totalTaxExpenses": -477081785345,	
                        "deferredIncomeTaxExpense": 26135956217	
                    },	
                    "netOperatingProfit": 3302799103110,	
                    "costOfSales": -30126073473488,	
                    "revenue": {	
                        "netRevenue": 34490982426689,	
                        "deductions": -741215175825,	
                        "grossRevenue": 35232197602514	
                    },	
                    "netProfitAfterTax": 2809594315351,	
                    "operatingIncomeExpenses": {	
                        "financialExpenses": {	
                            "totalFinancialExpenses": -1015139809937,    	
                            "interestExpenses": -562492663846	
                        },	
                        "sellingExpenses": -230212058532,	
                        "generalAndAdminExpenses": -517318083678,        	
                        "shareOfProfitInAssociates": 0,	
                        "financialIncome": 700560102056	
                    },	
                    "profitAttribution": {	
                        "attributableToParentCompany": 2808645369171,    	
                        "attributableToNonControllingInterest": 948946180	
                    },	
                    "otherIncomeExpenses": {	
                        "otherIncome": 225300683318,	
                        "otherExpenses": -241423685732,	
                        "netOtherIncomeExpenses": -16123002414	
                    },	
                    "grossProfit": 4364908953201,	
                    "netProfitBeforeTax": 3286676100696	
                }	
            ]	
        },	
        "companyType": "MANUFACTURING",	
        "businessTypeId": 3	
    }	
]	
```

### 2.2. Ngân hàng

```
[	
    {	
        "ticker": "VCB",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "incomeStatement": [	
                {	
                    "tradingAndInvestmentIncome": {	
                        "netGainLossFromInvestmentSecurities": 2735000000,	
                        "netGainLossFromTradingSecurities": 4472000000,	
                        "netGainLossFromForeignCurrencyAndGold": 1586183000000	
                    },	
                    "earningsPerShare": {	
                        "epsDiluted": 0,	
                        "epsBasic": 1050	
                    },	
                    "taxExpenses": {	
                        "currentIncomeTaxExpense": -2274403000000,	
                        "totalTaxExpenses": -2132756000000,	
                        "deferredIncomeTaxExpense": 141647000000	
                    },	
                    "operatingExpenses": -7040188000000,	
                    "interestIncome": {	
                        "interestAndSimilarIncome": 23581262000000,	
                        "netInterestIncome": 13842332000000,	
                        "interestAndSimilarExpenses": -9738930000000	
                    },	
                    "operatingProfitBeforeProvision": 10670348000000,	
                    "provisionForCreditLosses": 32329000000,	
                    "profitAttribution": {	
                        "attributableToParentCompany": 8565378000000,	
                        "nonControllingInterest": -4543000000	
                    },	
                    "netProfitBeforeTax": 10702677000000,	
                    "feeAndCommissionIncome": {	
                        "feesAndCommissionIncome": 3368816000000,	
                        "netFeeAndCommissionIncome": 923783000000,	
                        "feesAndCommissionExpenses": -2445033000000	
                    },	
                    "totalOperatingIncome": 17710536000000,	
                    "netProfitAfterTax": 8569921000000,	
                    "dividendsIncome": 66378000000,	
                    "otherIncomeExpenses": {	
                        "otherIncome": 1833975000000,	
                        "otherExpenses": -549322000000,	
                        "netOtherIncomeExpenses": 1284653000000	
                    }	
                }	
            ]	
        },	
        "companyType": "BANKING",	
        "businessTypeId": 1	
    }	
]	
```

### 2.3. Doanh nghiệp chứng khoán

```
[	
    {	
        "ticker": "SSI",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "incomeStatement": [	
                {	
                    "operatingIncome": {	
                        "revenueFromOtherOperatingActivities": 159228084869,	
                        "revenueFromBrokerageServices": 319081080523,	
                        "revenueFromStockInvestmentAdvisoryServices": 5076593090,      	
                        "gainFromLoansAndReceivables": 570733012956,	
                        "revenueFromUnderwritingServices": 9645301369,	
                        "revenueFromFinancialAdvisoryServices": 9909312725,	
                        "totalOperatingRevenue": 2221274987684,	
                        "gainFromFinancialAssetsAtFVTPL": {	
                            "dividendsAndInterestFromFVTPL": 458116449700,	
                            "gainFromDisposalOfFinancialAssetsAtFVTPL": 533797567725,  	
                            "gainFromRevaluationOfFinancialAssetsAtFVTPL": 77445924780,	
                            "totalGainFromFinancialAssetsAtFVTPL": 1069359942205       	
                        },	
                        "gainFromHeldToMaturityInvestments": 70365036207,	
                        "gainFromAvailableForSaleAFSFinancialAssets": -1920489739,     	
                        "gainFromDerivative": 0,	
                        "revenueFromSecuritiesCustodianServices": 9797113479	
                    },	
                    "earningsPerShare": {	
                        "netIncomeAvailableToCommonShareholders": 0,	
                        "dilutedEarningsPerShare": 0,	
                        "basicEarningsPerShare": 0	
                    },	
                    "taxExpenses": {	
                        "currentIncomeTaxExpense": -132825428063,	
                        "totalIncomeTaxExpenses": -116405977346,	
                        "deferredIncomeTaxExpense": 16419450717	
                    },	
                    "generalAndAdministrativeExpenses": -92749211365,	
                    "sellingExpenses": 0,	
                    "operatingExpenses": {	
                        "otherExpenses": {	
                            "totalOtherExpenses": -122952284234	
                        },	
                        "totalOperatingExpenses": -1205443690595,	
                        "expensesForSecuritiesInvestmentAdvisoryServices": -4615364040,	
                        "provisionExpenseForInvestmentLosses": -34746394527,	
                        "expensesForSecuritiesCustodianServices": -10506493998,        	
                        "expensesForBrokerageServices": -311643887858,	
                        "lossFromDerivative": 0,	
                        "expensesForProprietaryTradingActivities": -40974083587,       	
                        "lossFromHeldToMaturityInvestments": 0,	
                        "expensesForFinancialAdvisoryActivities": -9731408322,	
                        "lossFromFinancialAssetsAtFVTPL": {	
                            "totalLossFromFinancialAssetsAtFVTPL": -661210512559,	
                            "lossFromRevaluationOfFinancialAssetsAtFVTPL": -357736593994,	
                            "transactionCostOfAcquisitionOfFinancialAssetsAtFVTPL": -3721644754,	
                            "lossFromDisposalOfFinancialAssetsAtFVTPL": -299752273811	
                        },	
                        "expensesForUnderwritingAndIssuanceAgencyServices": -9063261470,	
                        "lossFromAvailableForSaleAFSFinancialAssets": 0	
                    },	
                    "otherIncomeAndExpenses": {	
                        "otherOperatingIncome": 746639592,	
                        "netOtherIncomeOrExpenses": -1340488587,	
                        "otherOperatingExpenses": -2087128179	
                    },	
                    "otherComprehensiveIncomeAfterTax": {	
                        "gainLossFromValuationOfDerivatives": 0,	
                        "totalOtherComprehensiveIncome": 9245392000,	
                        "gainLossDistributedFromInvestmentsInSubsidiariesAssociatesAndJointVentures": 0,	
                        "gainLossFromRevaluationOfAvailableForSalesFinancialAssets": 9245392000,	
                        "preDistributedGainLossFromInvestmentsInSubsidiariesAssociatesAndJointVentures": 0,	
                        "gainLossFromRevaluationOfDerivatives": 0,	
                        "gainLossFromForeignExchangeDifferenceOfOverseasOperations": 0,	
                        "gainLossFromRevaluationOfFixedAssetsUsingFairValueModel": 0	
                    },	
                    "profitBeforeTax": {	
                        "accountingProfitBeforeTax": 554769762801,	
                        "unrealizedProfitBeforeTax": -270310131826,	
                        "realizedProfitBeforeTax": 825079894627	
                    },	
                    "financialIncome": {	
                        "gainFromDisposalsOrSalesOfInvestmentsInSubsidiariesAssociatesAndJointVentures": 0,	
                        "totalFinancialIncome": 43964730178,	
                        "otherInvestmentIncome": 27178025374,	
                        "realizedAndUnrealizedGainFromChangesInForeignExchangesRates": 10168314028,	
                        "dividendInterestFromDemandDeposits": 6618390776	
                    },	
                    "comprehensiveIncome": {	
                        "totalComprehensiveIncome": 447609177455,	
                        "attributableToShareholders": 447609177455,	
                        "attributableToNonControllingInterests": 0	
                    },	
                    "profitAfterTax": {	
                        "profitAfterTaxAfterAppropriations": 0,	
                        "netProfitAfterTax": 438363785455,	
                        "profitAfterTaxAttributableToNoncontrollingInterest": 10625619023,	
                        "profitAfterTaxAttributableToTheParentCompanyOwners": 427738166432	
                    },	
                    "financialExpenses": {	
                        "totalFinancialExpenses": -410936564514,	
                        "interestExpenses": -405752832021,	
                        "shareOfProfitLossFromJointVentures": 0,	
                        "otherInvestmentExpenses": -2073184310,	
                        "provisionForInvestmentLoss": 0,	
                        "realizedAndUnrealizedLossFromChangesInForeignExchangesRates": -3110548183,	
                        "lossFromDisposalsOrSalesOfInvestmentsInSubsidiariesAssociatesAndJointVentures": 0	
                    },	
                    "grossProfit": 1015831297089,	
                    "operatingProfit": 556110251388	
                }	
            ]	
        },	
        "companyType": "SECURITIES",	
        "businessTypeId": 3	
    }	
]	
```

### 2.4. Doanh nghiệp bảo hiểm

```
[	
    {	
        "ticker": "BVH",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "incomeStatement": [	
                {	
                    "catastropheReserveExpenses": 0,	
                    "changeInClaimReserve": {	
                        "outwardReserveChange": -340255471042,	
                        "totalChangeInClaimReserve": -48478760054,	
                        "directAndInwardReserveChange": 291776710988        	
                    },	
                    "deductions": {	
                        "subrogationRecoveries": 0,	
                        "totalDeductions": 1185344534,	
                        "salvages": 1185344534,	
                        "recoveriesReinsuranceCeded": 0	
                    },	
                    "profitBeforeTax": 698671288788,	
                    "changeInCatastropheReserve": -13043873653,	
                    "otherInsuranceOperatingExpenses": {	
                        "directInsuranceExpenses": 0,	
                        "totalOtherExpenses": -895651685256,	
                        "reinsuranceAssumedExpenses": 0,	
                        "otherUnderwritingExpenses": {	
                            "riskMinimization": 0,	
                            "lossAdjustingAndRiskAssessment": 0,	
                            "commissions": -600541584531,	
                            "sellingExpenses": 0,	
                            "totalOtherUnderwritingExpenses": -895651685256,	
                            "thirdPartyRecourse": 0,	
                            "fullyIndemnifiedGoods": 0,	
                            "others": -295110100725	
                        },	
                        "reinsuranceCededExpenses": 0	
                    },	
                    "gainLossJointVentures": 35957841680,	
                    "profitAfterTax": {	
                        "attributableToParentCompany": 560335389500,        	
                        "netProfitAfterTax": 575011518636,	
                        "attributableToNonControllingInterests": 14676129136	
                    },	
                    "claimAndMaturityPaymentExpenses": -5320087494877,      	
                    "reinsurancePremiumCeded": {	
                        "otherCededPremiumDeductions": 0,	
                        "changeInUnearnedCededPremiumReserve": 1090256117,  	
                        "totalReinsurancePremiumCeded": -882898418406,      	
                        "cededPremiumRefunds": 0,	
                        "reinsurancePremiumCeded": -883988674523	
                    },	
                    "earningsPerShare": {	
                        "ePSDiluted": 0,	
                        "ePSBasic": 755	
                    },	
                    "taxExpenses": {	
                        "currentIncomeTaxExpense": -118793503363,	
                        "totalTaxExpenses": -123659770152,	
                        "deferredIncomeTaxExpense": -4866266789	
                    },	
                    "insurancePremium": {	
                        "reinsurancePremiumAssumed": 64803201619,	
                        "changeInUnearnedPremiumReserve": -46123818050,	
                        "totalRevenueFromInsurancePremium": 11165344381246,	
                        "directWrittenPremium": 11146664997677	
                    },	
                    "otherActivities": {	
                        "incomeFromOtherActivities": 98264493429,	
                        "expensesFromOtherActivities": -124231299550,	
                        "netOperatingIncomeOther": -25966806121	
                    },	
                    "grossInsuranceOperatingProfit": 67149647564,	
                    "generalAndAdminExpenses": {	
                        "otherOperations": 0,	
                        "bankingOperation": 0,	
                        "insuranceOperation": -1560836151613,	
                        "totalGeneralAndAdmin": -1560836151613	
                    },	
                    "sellingExpenses": -409320319252,	
                    "equalisationReserve": 0,	
                    "netInsurancePremium": 10282445962840,	
                    "recoveriesFromReinsuranceCeded": 455031247569,	
                    "commissionAndOtherIncome": {	
                        "otherIncome": {	
                            "totalOtherIncome": 0,	
                            "reinsuranceAssumedIncome": 0,	
                            "reinsuranceCededIncome": 0,	
                            "otherActivitiesIncome": 0	
                        },	
                        "totalCommissionAndOtherIncome": 184933662369,	
                        "commissionOnReinsuranceCeded": 184933662369	
                    },	
                    "financialActivities": {	
                        "profitFinancialActivities": 2579764071055,	
                        "financialExpenses": -629539261479,	
                        "financialIncome": 3209303332534	
                    },	
                    "netRevenueFromInsuranceBusiness": 10467379625209,	
                    "claimExpensesReinsuranceAssumed": -32006260964,	
                    "totalDirectInsuranceExpenses": -10400229977645,	
                    "realEstateActivities": {	
                        "costRealEstate": 0,	
                        "revenueRealEstate": 0,	
                        "realEstateInvestmentProfits": 0	
                    },	
                    "changeInMathematicsReserves": -4547178494944,	
                    "totalInsuranceClaimSettlementExpenses": -9491534418736,	
                    "operatingProfitFromInsuranceOperation": {	
                        "netOperatingProfitFromInsuranceOperation": -1903006823301,	
                        "gainLossFromNonLifeInsurance": -1903006823301,	
                        "gainLossFromLifeInsurance": 0	
                    },	
                    "bankingActivities": {	
                        "expensesBanking": 0,	
                        "netOperatingIncomeBanking": 0,	
                        "incomeBanking": 0	
                    },	
                    "increaseInUnearnedPremiumReserveAndTechnical": 0,	
                    "otherIncomeExpenses": {	
                        "otherIncome": 13474172215,	
                        "otherExpenses": -1551166740,	
                        "netOtherIncome": 11923005475	
                    },	
                    "claimExpensesRetainedRisks": -4895877163738	
                }	
            ]	
        },	
        "companyType": "INSURANCE",	
        "businessTypeId": 1	
    }	
]	
```

## <mark style="color:purple;">3. Báo cáo lưu chuyển tiền tệ</mark>

### 3.1. Doanh nghiệp sản xuất

```
[	
    {	
        "ticker": "HPG",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "cashFlow": [	
                {	
                    "cashAndCashEquivalentsAtTheEndOfPeriod": 6887646139852,      	
                    "cashAndCashEquivalentsAtTheBeginningOfPeriod": 8500998079280,	
                    "cashFlowsFromInvestingActivities": {	
                        "proceedsFromDisposalOfFixedAssets": 443699573180,        	
                        "purchasesOfFixedAndLongTermAssets": -7257089099480,      	
                        "proceedsFromDivestmentInOtherEntities": 31246619001,     	
                        "investmentsInOtherEntities": 0,	
                        "netCashFromInvestingActivities": -9083163490691,	
                        "loansGrantedPurchasesOfDebtInstruments": -6360476824332,	
                        "dividendsAndInterestReceived": 187519990129,	
                        "collectionOfLoansSalesOfDebtInstruments": 3871936250811  	
                    },	
                    "effectOfForeignExchangeDifferences": 5563161728,	
                    "netCashFlow": -1618915101156,	
                    "cashFlowsFromOperatingActivities": {	
                        "operatingProfitBeforeChanges": {	
                            "changesInReceivables": 971968926351,	
                            "operatingProfitBeforeChanges": 4955838305029,        	
                            "changesInPrepaidExpenses": 129299221688,	
                            "changesInTradingSecurities": 0,	
                            "changesInPayables": 4023222874211,	
                            "incomeTaxPaid": -51647870077,	
                            "otherPaymentsOnOperatingActivities": -194420019511,  	
                            "changesInInventories": -6209983876378,	
                            "otherReceiptsFromOperatingActivities": 447272727,    	
                            "interestPaid": -529644932828	
                        },	
                        "adjustments": {	
                            "depreciationAndAmortisation": 1693028331093,	
                            "provisions": -61035121811,	
                            "unrealisedForeignExchangeGainLoss": 227751228845,    	
                            "amortisationOfGoodwill": 12295891969,	
                            "otherAdjustments": 0,	
                            "profitLossFromInvestingActivities": -765370789609,   	
                            "interestExpense": 562492663846	
                        },	
                        "netCashFromOperatingActivities": 3095079901212,	
                        "profitBeforeTax": 3286676100696	
                    },	
                    "cashFlowsFromFinancingActivities": {	
                        "proceedsFromIssueOfShares": 103000000000,	
                        "dividendsPaid": -2343960741,	
                        "netCashFromFinancingActivities": 4369168488323,	
                        "proceedsFromLoans": 42414841815225,	
                        "repaymentOfLoans": -38146312226161,	
                        "financeLeasePrincipalPayments": 0,	
                        "paymentsForShareReturnsAndRepurchases": -17140000	
                    }	
                }	
            ]	
        },	
        "companyType": "MANUFACTURING",	
        "businessTypeId": 3	
    }	
]	
```

### 3.2. Ngân hàng

```
[	
    {	
        "ticker": "VCB",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "cashFlow": [	
                {	
                    "cashAndCashEquivalentsAtTheEndOfPeriod": 430614185000000,	
                    "cashAndCashEquivalentsAtTheBeginningOfPeriod": 314023125000000,	
                    "cashFlowsFromInvestingActivities": {	
                        "proceedsFromDisposalOfInvestmentProperties": 0,	
                        "proceedsFromDisposalOfFixedAssets": 5492000000,	
                        "purchasesOfInvestmentProperties": 0,	
                        "proceedsFromDivestmentInOtherEntities": 0,	
                        "paymentsOnDisposalOfInvestmentProperties": 0,	
                        "investmentsInOtherEntities": 0,	
                        "paymentsForPurchasesOfFixedAssetsAndOtherLongTermAssets": -531176000000,	
                        "paymentsOnDisposalOfFixedAssets": -809000000,	
                        "netCashFromInvestingActivities": -501783000000,	
                        "dividendsAndInterestReceived": 24710000000	
                    },	
                    "effectOfForeignExchangeDifferences": 0,	
                    "netCashFlow": 116591060000000,	
                    "cashFlowsFromOperatingActivities": {	
                        "netFeeAndCommissionIncomeReceived": 570544000000,	
                        "interestAndSimilarIncomeReceived": 23060402000000,	
                        "interestAndSimilarExpensesPaid": -9657477000000,	
                        "netReceiptsFromTradingActivities": 1303964000000,	
                        "cashFlowFromOperatingActivitiesBeforeChangesInOperatingAssetsAndLiabilities": 10425121000000,	
                        "netCashFromOperatingActivities": 117112806000000,	
                        "changesInOperatingLiabilities": {	
                            "changesInDepositsAndBorrowingsToOtherCreditInstitutions": 17273590000000,	
                            "changesInDerivativesAndOtherFinancialLiabilities": -116988000000,	
                            "changesInFundsFromGovAndInstitutions": 527000000,	
                            "paymentFromReserves": -646942000000,	
                            "changesInDepositsFromCustomers": 84593830000000,	
                            "changesInLoansFromStateAndSBV": 41944064000000,	
                            "changesInValuablePapersIssued": -2776436000000,	
                            "changesInOtherOperatingLiabilities": 2376448000000	
                        },	
                        "changesInOperatingAssets": {	
                            "derivativesAndOtherFinancialAssets": -1314434000000,	
                            "changeInLoansToCustomers": -48047224000000,	
                            "changesInDepositsAndLoansToOtherCreditInstitutions": 6503970000000,	
                            "changesInHeldForTradingSecuritiesAndInvestmentSecurities": 2299942000000,	
                            "provisionForLoanLosses": -3877864000000,	
                            "changesInOtherOperatingAssets": 8475202000000	
                        },	
                        "corporateIncomeTaxPaid": -81798000000,	
                        "otherIncomeExpenses": -343813000000,	
                        "salariesAndOperatingExpensesPaid": -6050484000000,	
                        "receiptsFromDebtsWrittenOff": 1623783000000	
                    },	
                    "cashFlowsFromFinancingActivities": {	
                        "paymentsForRedemptionOfBonds": 0,	
                        "proceedsFromIssueOfShares": 0,	
                        "proceedsFromConvertibleBonds": 0,	
                        "dividendsPaid": -19963000000,	
                        "netCashFromFinancingActivities": -19963000000,	
                        "purchaseOfTreasuryShares": 0,	
                        "proceedsFromSellingTreasuryShares": 0	
                    }	
                }	
            ]	
        },	
        "companyType": "BANKING",	
        "businessTypeId": 1	
    }	
]	
```

### 3.3. Doanh nghiệp chứng khoán

```
[	
    {	
        "ticker": "SSI",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "cashFlow": [	
                {	
                    "cashAndCashEquivalentsAtTheEndOfPeriod": {	
                        "cashEquivalents": 30030246575,	
                        "totalCashAndCashEquivalentsAtTheEndOfPeriod": 239000238200,	
                        "effectOfForeignExchangeDifferences": 2174347516,	
                        "cash": 206795644109	
                    },	
                    "cashAndCashEquivalentsOfCustomersAtTheBeginningOfPeriod": {	
                        "cashEquivalent": 0,	
                        "totalCashAndCashEquivalentsOfCustomersAtTheBeginningOfPeriod": 6343236859628,	
                        "effectOfForeignExchangeDifferences": 0,	
                        "cashAndBankDeposit": {	
                            "investorDepositSecuritiesCompanyMethod": {	
                                "investorDepositWithTerm": 0,	
                                "totalInvestorDepositSecuritiesCompanyMethod": 6319318004994	
                            },	
                            "depositsOfSecuritiesIssuers": {	
                                "totalDepositsOfSecuritiesIssuers": 11708460936,	
                                "issuingOrganizationDepositWithTerm": 0	
                            },	
                            "depositForSecuritiesClearing": 0,	
                            "customersGeneralDeposit": 12210393698,	
                            "totalCashAndBankDeposit": 6343236859628	
                        }	
                    },	
                    "cashAndCashEquivalentsOfCustomersAtTheEndOfPeriod": {	
                        "cashEquivalent": 0,	
                        "totalCashAndCashEquivalentsOfCustomersAtTheEndOfPeriod": 4941400793936,      	
                        "effectOfForeignExchangeDifferences": 0,	
                        "cashAndBankDeposit": {	
                            "investorDepositSecuritiesCompanyMethod": {	
                                "investorDepositWithTerm": 0,	
                                "totalInvestorDepositSecuritiesCompanyMethod": 4919023915622	
                            },	
                            "depositsOfSecuritiesIssuers": {	
                                "totalDepositsOfSecuritiesIssuers": 11297197134,	
                                "issuingOrganizationDepositWithTerm": 0	
                            },	
                            "depositForSecuritiesClearing": 0,	
                            "customersGeneralDeposit": 11079681180,	
                            "totalCashAndBankDeposit": 4941400793936	
                        }	
                    },	
                    "cashAndCashEquivalentsAtTheBeginningOfPeriod": {	
                        "cashEquivalents": 0,	
                        "effectOfForeignExchangeDifferences": 512993328,	
                        "cash": 660773688392,	
                        "totalCashAndCashEquivalentsAtTheBeginningOfPeriod": 661286681720	
                    },	
                    "cashFlowsFromInvestingActivities": {	
                        "proceedsFromDisposalOfFixAssetsAndInvestmentPropertiesAndOtherLongTermAssets": 83484415636,	
                        "collectionOfLoansAndProceedsFromSalesOfDebtsInstruments": 0,	
                        "proceedsFromDivestmentInOtherEntities": 0,	
                        "purchasesAndConstructionOfFixedAssetsAndInvestmentPropertiesAndOtherLongTermAssets": -290162312537,	
                        "investmentsInOtherEntities": -820000000000,	
                        "netCashFromInvestingActivities": -1026677896901,	
                        "dividendsAndInterestReceived": 0,	
                        "loansGrantedAndPurchasesOfDebtInstruments": 0	
                    },	
                    "cashFlowsFromBrokerageAndTrustActivities": {	
                        "cashReceivedForThePurposeOfMandatedInvestmentOfClients": -50024721687,	
                        "cashPaidOnTransactionErrors": 0,	
                        "cashInflowFromMandatedSales": 0,	
                        "cashInflowFromCurrentAccountOfClients": 0,	
                        "cashPaidForThePurposeOfClientsTransactionSettlement": -167590257153513,	
                        "cashReceivedOnTransactionErrors": 0,	
                        "cashOutflowFromCurrentAccountOfClients": 0,	
                        "cashInflowOnLoanFromSettlementAssistanceFund": 0,	
                        "cashOutflowFromSecuritiesPurchase": -106053636536510,	
                        "cashPaidForDepositoryFee": -8838075903,	
                        "cashInflowFromSecuritiesBroking": 112446988164988,	
                        "cashOutflowFromMandatedSales": 0,	
                        "cashPaidForThePurposeOfMandatedInvestmentOfClients": 0,	
                        "netCashFromBrokerageAndTrustActivities": -1401836065692,	
                        "cashReceivedForPurposeOfTransactionsOfClients": 160188523820216,	
                        "cashReceivedFromIssuingOrganizations": 1128179917000,	
                        "cashOutflowOnRepayingFromSettlementAssistanceFund": 0,	
                        "cashPaidToIssuingOrganizations": -1462771480283	
                    },	
                    "netCashFlow": -422286443520,	
                    "cashFlowsFromOperatingActivities": {	
                        "decreaseInNonMonetaryRevenue": {	
                            "reversalOfProvision": 0,	
                            "gainFromRevaluationOfFinancialAssetsAtFVTPL": -77445924780,	
                            "totalDecreaseInNonMonetaryRevenue": -77445924780,	
                            "gainFromAFSReclassification": 0,	
                            "otherGains": 0	
                        },	
                        "operatingProfitBeforeChanges": {	
                            "operatingProfitBeforeChanges": -6542795640146,	
                            "changesInPrepaidExpenses": -5864781300,	
                            "changesInTaxAndPayablesToAuthority": 17167054630,	
                            "changesInFVTPLFinancialAssets": -5337039144331,	
                            "changesInAvailableForSaleFinancialAssets": 3235887200,	
                            "changesInTradePayables": -94364324227,	
                            "interestExpensesPaid": -386222868753,	
                            "incomeTaxPaid": -173297277481,	
                            "changesInPayableExpensesExcludingInterest": -26530110226,	
                            "changesInOtherReceivables": -402214172791,	
                            "changesInOtherAssets": 90249742232,	
                            "changesInPayableFromFinancialAssetTransactionError": 0,	
                            "changesInHeldToMaturityInvestments": 1596096206907,	
                            "changesInPayablesToEmployees": 45161121770,	
                            "changesInLoansGiven": -2500301689956,	
                            "otherPayments": {	
                                "otherExpenses": -2918076634,	
                                "totalOtherPayments": -2918076634,	
                                "businessIncomeTaxPaid": 0,	
                                "interestPaid": 0	
                            },	
                            "changesInReceivableFromSellingFinancialAssets": -276145542000,	
                            "changesInEmployeesWelfareContributions": -190110604,	
                            "changesInReceivableFromInterestOfFinancialAssets": 0,	
                            "changesInReceivableFromTransactionErrors": 0,	
                            "changesInOtherPayables": -115346181038,	
                            "otherReceipts": {	
                                "interestReceived": 0,	
                                "totalOtherReceipts": 1036691380044,	
                                "otherReceivables": 1036691380044	
                            },	
                            "changesInReceivableFromServicesRendered": -10962753588	
                        },	
                        "adjustments": {	
                            "depreciationAndAmortisation": 23294171773,	
                            "provisions": 34762788174,	
                            "totalAdjustments": -664031531181,	
                            "unrealisedForeignExchangeGainLoss": -9980537388,	
                            "interestIncomeAndDividend": -1026919751205,	
                            "amortisationOfGoodwill": 0,	
                            "accruedExpenses": 0,	
                            "otherAdjustments": 2956074154,	
                            "profitLossFromInvestingActivities": -93897108710,	
                            "interestExpense": 405752832021	
                        },	
                        "netCashFromOperatingActivities": -6369727968576,	
                        "increaseInNonMonetaryExpenses": {	
                            "lossOnHeldToMaturityInvestments": 0,	
                            "otherLoss": 2035000000,	
                            "provisionForLongTermInvestments": 0,	
                            "lossFromRevaluationOfFinancialAssetsAtFVTPL": 357736593994,	
                            "lossOnAFSReclassification": 0,	
                            "lossOnLoansGiven": 3770736,	
                            "totalIncreaseInNonMonetaryExpenses": 359775364730	
                        },	
                        "netProfitBeforeTax": 554769762801	
                    },	
                    "cashFlowsFromFinancingActivities": {	
                        "proceedsFromIssueOfShares": 2263708005000,	
                        "dividendsPaid": -1505372068000,	
                        "netCashFromFinancingActivities": 6974119421957,	
                        "repaymentOfLoans": {	
                            "financialAssetsLoans": 0,	
                            "otherLoans": -66794440486399,	
                            "totalRepaymentOfLoans": -66794440486399,	
                            "settlementAssistanceFund": 0	
                        },	
                        "proceedsFromLoans": {	
                            "otherLoans": 73010223971356,	
                            "settlementAssistanceFund": 0,	
                            "totalProceedsFromLoans": 73010223971356	
                        },	
                        "financeLeasePrincipalPayments": 0,	
                        "paymentsForShareReturnsAndRepurchases": 0	
                    }	
                }	
            ]	
        },	
        "companyType": "SECURITIES",	
        "businessTypeId": 3	
    }	
]		
```

### 3.4. Doanh nghiệp bảo hiểm

```
[	
    {	
        "ticker": "BVH",	
        "year": 2024,	
        "quarter": 4,	
        "reportType": "consolidated",	
        "audited": true,	
        "financialStatement": {	
            "cashFlow": [	
                {	
                    "cashAndCashEquivalentsAtTheEndOfPeriod": 1464088127113,	
                    "cashAndCashEquivalentsAtTheBeginningOfPeriod": 2492005463163,	
                    "cashFlowsFromInvestingActivities": {	
                        "collectionOfLoansAndProceedsFromSalesOfDebtsInstruments": 16547744977558,	
                        "loansGrantedAndDebtInstrumentsPurchased": -31477820550999,	
                        "purchasesAndConstructionOfFixedAndLongTermAssets": -43750705265,	
                        "proceedsFromDisposalOfFixedAndLongTermAssets": 431618182,	
                        "proceedsFromDivestmentInOtherEntities": 0,	
                        "investmentsInOtherEntities": -245308499,	
                        "netCashFromInvestingActivities": -12031799087740,	
                        "dividendsAndInterestReceived": 2941840881283	
                    },	
                    "effectOfForeignExchangeDifferences": 190850472,	
                    "netCashFlow": -1028108186522,	
                    "cashFlowsFromOperatingActivities": {	
                        "operatingProfitBeforeChanges": {	
                            "changesInReceivables": {	
                                "reinsuranceAssumedReceivables": 0,	
                                "otherReceivablesFromInsurance": 1238632024209,	
                                "reinsuranceCededReceivables": 0,	
                                "interCompanyReceivablesPayables": 0,	
                                "totalChangesInReceivables": 1238632024209,	
                                "grossWrittenPremiumReceivables": 0	
                            },	
                            "payablesExcludingInterestAndTax": {	
                                "grossWrittenPremiumPayables": 0,	
                                "reinsuranceCededPayables": 0,	
                                "payablesToEmployees": 0,	
                                "otherPayablesFromInsurance": -481523964546,	
                                "reinsuranceAssumedPayables": 0,	
                                "totalChangesInPayables": -481523964546	
                            },	
                            "operatingProfitBeforeChanges": 2236492652239,	
                            "changesInPrepaidExpenses": -121078201649,	
                            "changesInTradingSecurities": 23790361850,	
                            "otherPaymentsOnOperatingActivities": -13300685403,	
                            "changesInInventories": -8633811127,	
                            "corporateIncomeTaxPaid": -119757549110,	
                            "otherReceiptsFromOperatingActivities": 0,	
                            "interestPaid": -31640508878	
                        },	
                        "adjustments": {	
                            "depreciationAndAmortisation": 114024389779,	
                            "provisions": 4332402833531,	
                            "unrealisedForeignExchangeGainLoss": 6037995155,	
                            "interestIncomeAndDividend": 0,	
                            "amortisationOfGoodwill": 0,	
                            "otherAdjustments": 0,	
                            "profitLossFromInvestingActivities": -3235181137860,	
                            "repoAndInterestExpenses": 320537282846	
                        },	
                        "netCashFromOperatingActivities": 2722980317585,	
                        "netProfitBeforeTax": 698671288788	
                    },	
                    "cashFlowsFromFinancingActivities": {	
                        "proceedsFromIssueOfShares": 0,	
                        "dividendsPaid": -767074656367,	
                        "netCashFromFinancingActivities": 8280710583633,	
                        "proceedsFromLoans": 12228301080000,	
                        "repaymentOfLoans": -3180515840000,	
                        "financeLeasePrincipalPayments": 0,	
                        "paymentsForShareReturnsAndRepurchases": 0	
                    }	
                }	
            ]	
        },	
        "companyType": "INSURANCE",	
        "businessTypeId": 1	
    }	
]	
```


# Mô tả dữ liệu giao dịch

<table><thead><tr><th width="69.69140625">Stt</th><th width="196.90625">Nhóm dữ liệu</th><th width="290">Chi tiết</th><th width="155.48828125">Trạng thái: EOD</th><th width="283.984375">Trạng thái: Tick-by-Tick (Websocket)</th><th width="270.828125">Trạng thái: Intraday (1' 5' 15' 1h 4h) </th></tr></thead><tbody><tr><td>1</td><td>Giá &#x26; Khối lượng &#x26; Giá trị giao dịch</td><td>OHLCV (Open - High - Low - Close - Volume), giá trị giao dịch (Value), dữ liệu realtime &#x26; lịch sử.</td><td>Có</td><td>Có</td><td>Có</td></tr><tr><td>2</td><td>Sổ lệnh (Order Book)</td><td>Dữ liệu 3/10 mức giá mua – bán, volume bid/ask.</td><td></td><td>Có</td><td></td></tr><tr><td>3</td><td>Dòng tiền chủ động</td><td>Mua chủ động/Bán chủ động</td><td>Có</td><td>Có</td><td>Có</td></tr><tr><td>4</td><td>Giao dịch khối ngoại</td><td>Mua bán ròng theo từng mã</td><td>Có</td><td>Có</td><td>Có</td></tr><tr><td>5</td><td>Chỉ số tái cân bằng</td><td>Danh sánh mã theo rổ chỉ số. Chỉ số Freeloat, Outstanding Share, Marketcap Limit đối với các mã trong rổ chỉ số</td><td>Có</td><td></td><td></td></tr><tr><td>6</td><td>Bộ chỉ số PTKT</td><td></td><td>Có</td><td>Có</td><td>Có</td></tr></tbody></table>

### Bảng data realtime tick-by-tick

<table><thead><tr><th width="87.9140625">Stt</th><th width="224.109375">Tên cột</th><th width="332.6171875">Mô tả</th><th width="97">Kiểu dữ liệu</th></tr></thead><tbody><tr><td>1</td><td>Ticker</td><td>Tên mã</td><td>Str</td></tr><tr><td>2</td><td>TotalMatchVolume</td><td>Tổng khối lượng khớp lệnh</td><td>Int</td></tr><tr><td>3</td><td>MarketStatus</td><td>Trạng thái thị trường</td><td>Str</td></tr><tr><td>4</td><td>TradingDate</td><td>Thời gian khớp lệnh</td><td>Str</td></tr><tr><td>5</td><td>ComGroupCode</td><td>Mã chỉ số</td><td>Str</td></tr><tr><td>6</td><td>Reference</td><td>Giá trị tham chiếu</td><td>Str</td></tr><tr><td>7</td><td>Open</td><td>Giá mở cửa</td><td>Float</td></tr><tr><td>8</td><td>Close</td><td>Giá đóng cửa</td><td>Float</td></tr><tr><td>9</td><td>High</td><td>Giá cao nhất</td><td>Float</td></tr><tr><td>10</td><td>Low</td><td>Giá thấp nhất</td><td>Float</td></tr><tr><td>11</td><td>Change</td><td>Giá trị thay đổi so với tham chiếu</td><td>Float</td></tr><tr><td>12</td><td>ChangePercent</td><td>Phần trăm giá trị thay đổi so với tham chiếu</td><td>Float</td></tr><tr><td>13</td><td>MatchVolume</td><td>Khối lượng khớp lệnh</td><td>Int</td></tr><tr><td>14</td><td>MatchValue</td><td>Giá trị khớp lệnh</td><td>Float</td></tr><tr><td>15</td><td>TotalMatchValue</td><td>Tổng giá trị khớp lệnh</td><td>Float</td></tr><tr><td>16</td><td>TotalBuyTradeVolume</td><td>Tổng khối lượng mua vào</td><td>Int</td></tr><tr><td>17</td><td>TotalSellTradeVolume</td><td>Tổng khối lượng bán ra</td><td>Int</td></tr><tr><td>18</td><td>TotalDealVolume</td><td>Tổng khối lượng khớp lệnh thỏa thuận</td><td>Int</td></tr><tr><td>19</td><td>TotalDealValue</td><td>Tổng giá trị khớp lệnh thỏa thuận</td><td>Float</td></tr><tr><td>20</td><td>ForeignBuyVolumeTotal</td><td>Tổng khối lượng mua ngoại từ đầu ngày</td><td>Int</td></tr><tr><td>21</td><td>ForeignBuyValueTotal</td><td>Tổng giá trị mua ngoại từ đầu ngày</td><td>Float</td></tr><tr><td>22</td><td>ForeignSellVolumeTotal</td><td>Tổng khối lượng bán ngoại từ đầu ngày</td><td>Int</td></tr><tr><td>23</td><td>ForeignSellValueTotal</td><td>Tổng giá trị bán ngoại từ đầu ngày</td><td>Float</td></tr></tbody></table>

### Bảng data dữ liệu lịch sử

<table><thead><tr><th width="103.6015625">Stt</th><th width="157">Tên thuộc tính</th><th width="290">Mô tả</th><th width="97">Kiểu dữ liệu</th></tr></thead><tbody><tr><td>1</td><td>ticker</td><td>Tên mã</td><td>Str</td></tr><tr><td>2</td><td>timestamp</td><td>Thời gian giao dịch</td><td>Int</td></tr><tr><td>3</td><td>open</td><td>Giá mở cửa</td><td>Float</td></tr><tr><td>4</td><td>close</td><td>Giá đóng cửa</td><td>Float</td></tr><tr><td>5</td><td>high</td><td>Giá cao nhất</td><td>Float</td></tr><tr><td>6</td><td>low</td><td>Giá thấp nhất</td><td>Float</td></tr><tr><td>7</td><td>volume</td><td>Khối lượng giao dịch</td><td>Int</td></tr><tr><td>8</td><td>value</td><td>Giá trị giao dịch</td><td>Int</td></tr><tr><td>9</td><td>bu</td><td>Khối lượng mua chủ động</td><td>Int</td></tr><tr><td>10</td><td>sd</td><td>Khối lượng bán chủ động</td><td>Int</td></tr><tr><td>11</td><td>fb</td><td>Giá trị mua khối ngoại</td><td>Int</td></tr><tr><td>12</td><td>fs</td><td>Giá trị bán khối ngoại</td><td>Int</td></tr><tr><td>13</td><td>fn</td><td>Giá trị mua/bán ròng</td><td>Int</td></tr></tbody></table>

### Bảng data nối dữ liệu Realtime và lịch sử

<table><thead><tr><th width="108.765625">Stt</th><th width="157">Tên thuộc tính</th><th width="290">Mô tả</th><th width="97">Kiểu dữ liệu</th></tr></thead><tbody><tr><td>1</td><td>ticker</td><td>Tên mã</td><td>Str</td></tr><tr><td>2</td><td>timestamp</td><td>Thời gian giao dịch</td><td>Int</td></tr><tr><td>3</td><td>open</td><td>Giá mở cửa</td><td>Float</td></tr><tr><td>4</td><td>close</td><td>Giá đóng cửa</td><td>Float</td></tr><tr><td>5</td><td>high</td><td>Giá cao nhất</td><td>Float</td></tr><tr><td>6</td><td>low</td><td>Giá thấp nhất</td><td>Float</td></tr><tr><td>7</td><td>volume</td><td>Khối lượng giao dịch</td><td>Int</td></tr><tr><td>8</td><td>value</td><td>Giá trị giao dịch</td><td>Int</td></tr><tr><td>9</td><td>bu</td><td>Khối lượng mua chủ động</td><td>Int</td></tr><tr><td>10</td><td>sd</td><td>Khối lượng bán chủ động</td><td>Int</td></tr><tr><td>11</td><td>fb</td><td>Giá trị mua khối ngoại</td><td>Int</td></tr><tr><td>12</td><td>fs</td><td>Giá trị bán khối ngoại</td><td>Int</td></tr><tr><td>13</td><td>fn</td><td>Giá trị mua/bán ròng</td><td>Int</td></tr></tbody></table>


# Chỉ số cơ bản


# Mô tả trường dữ liệu chỉ số báo cáo tài chính gói nâng cao

* Loại hình doanh nghiệp: CTCK, NH, BH, CTY
* Doanh nghiệp mẫu: HPG, SSI, VCB, BVH

List các dictionary, trong đó mỗi dictionary sẽ tương ứng với data của 1 kỳ báo cáo

## <mark style="color:purple;">1. Doanh nghiệp sản xuất</mark>

```json
[
    {
        "ratios": {
            "ActivityRatio": {
                "TotalAssetTurnover": 0.67360875,
                "FixedAssetTurnover": 1.99746402,
                "DaysOfSalesOutstanding": 13.60541001,
                "DaysOfInventoryOnHand": 122.5495936,
                "NumberOfDaysOfPayables": 40.08278741,
                "CashConversionCycle": 96.0722162
            },
            "LiquidityRatio": {
                "CashRatio": 0.0915603,
                "QuickRatio": 0.19322565,
                "CurrentRatio": 1.15219669
            },
            "SolvencyRatio": {
                "DebtToEquityRatio": 0.72363689,
                "LiabilitiesToEquityRatio": 0.95808709,
                "FinancialLeverageRatio": 1.95808709,
                "EBITInterestCoverage": 6.38933934
            },
            "ProfitabilityRatio": {
                "GrossProfitMargin": 0.13321475,
                "EBITMargin": 0.10525161,
                "NetProfitMargin": 0.08656522,
                "ROA": 0.05831798,
                "ROE": 0.11073185,
                "ROIC": 0.07400689
            },
            "ValuationRatios": {
                "MarketCap": 171419505360000.0,
                "BookValuePerShare": 17878.67325004,
                "BasicEPS": 1879.45178193,
                "PriceToBook": 1.49899266,
                "PriceToEarning": 14.25947729,
                "PriceToSales": 1.23452066,
                "EVtoEBITDA": 11.50865884,
                "PriceToCashFlow": -31.95073084
            },
            "Growth": {
                "NetRevenueGrowthYoY": 0.16731045,
                "EBTgrowthYoY": 0.75721531
            },
            "Revenue": 140561387448572.0,
            "AttributeToParentCompany": 12021443836074.0,
            "EBIT": 14614724419648.0
        },
        "ticker": "HPG",
        "year": 2024
    }
]
```

## <mark style="color:purple;">2. Ngân hàng</mark>

```json
[
    {
        "ratios": {
            "CapitalAdequacyComponent": {
                "CAR": 0.1216
            },
            "AssetQualityComponent": {
                "ProblemLoansAndLeasesCalculatedAsPercentageOfGrossLoans": 0.00963568,
                "LoanLossReservesToNPLs": 2.23310969,
                "LoanLossProvisionsCalculatedAsPercentageOfGrossLoansToCustomer": 0.02151753,
                "ProvisionChargesToLoans": 0.00177474,
                "CASARatio": 0.3497396
            },
            "EfficiencyComponent": {
                "NonInterestIncomeToNetInterestIncome": 0.23775086,
                "CostToIncomeRatio": 0.3357811
            },
            "LiquidityAndAssetsComponent": {
                "LDRPercentage": 0.80842175
            },
            "ProfitabilityComponent": {
                "NIM": 0.02860674,
                "AverageYieldOnEarningAssets": 0.04844275,
                "AverageCostOfFinancing": 0.02196457,
                "PreprovisionROA": 0.02320723,
                "PreprovisionROE": 0.25215852
            },
            "GrowthComponent": {
                "AverageLoansGrowthPercentageYoY": 0.14201639,
                "AverageDepositGrowthPercentageYoY": 0.08523855,
                "InterestincomeGrowthPercentageYoY": 0.03341086
            },
            "NetInterestIncome": 55405735000000.0,
            "AttributeToParentCompany": 33831386000000.0
        },
        "ticker": "VCB",
        "year": 2024
    }
]
```

## <mark style="color:purple;">3. Doanh nghiệp chứng khoán</mark>

```json
[
    {
        "ratios": {
            "ActivityRatio": {
                "TotalAssetTurnover": 0.11950069,
                "FixedAssetTurnover": 58.64222268
            },
            "LiquidityRatio": {
                "CashRatio": 1.48353629,
                "QuickRatio": 1.50071706,
                "CurrentRatio": 1.52217267
            },
            "SolvencyRatio": {
                "DebtToEquityRatio": 1.696148,
                "LiabilitiesToEquityRatio": 1.74008499,
                "FinancialLeverageRatio": 2.74008499,
                "EBITInterestCoverage": 3.28043821
            },
            "ProfitabilityRatio": {
                "GrossProfitMargin": 0.61450887,
                "EBITMargin": 0.57913078,
                "NetProfitMargin": 0.33356968,
                "ROA": 0.0397205,
                "ROE": 0.11391035,
                "ROIC": 0.05747587
            },
            "ValuationRatios": {
                "MarketCap": 61174361045700.0,
                "BookValuePerShare": 13583.44192478,
                "BasicEPS": 1443.59448452,
                "PriceToBook": 2.2932332,
                "PriceToEarning": 21.57808189,
                "PriceToSales": 7.17227762,
                "EVtoEBITDA": 21.11853306,
                "PriceToCashFlow": -239.98858965
            },
            "Growth": {
                "NetRevenueGrowthYoY": 0.19162418,
                "EBTgrowthYoY": 0.24396847
            },
            "Revenue": 8529279575474.0,
            "AttributeToParentCompany": 2835023120364.0,
            "EBIT": 4939568329540.0
        },
        "ticker": "SSI",
        "year": 2024
    }
]
```

## <mark style="color:purple;">4. Doanh nghiệp bảo hiểm</mark>

```json
[
    {
        "ratios": {
            "ActivityRatio": {
                "TotalAssetTurnover": 0.16858292,
                "FixedAssetTurnover": 43.51112659
            },
            "LiquidityRatio": {
                "CashRatio": 0.12547497,
                "QuickRatio": 0.40792562,
                "CurrentRatio": 2.96829948
            },
            "SolvencyRatio": {
                "DebtToEquityRatio": 0.12349318,
                "LiabilitiesToEquityRatio": 9.66313889,
                "FinancialLeverageRatio": 10.66313889
            },
            "ProfitabilityRatio": {
                "GrossProfitMargin": -0.0243354,
                "EBITMargin": -0.20190535,
                "NetProfitMargin": 0.05509778,
                "ROA": 0.00893434,
                "ROE": 0.09603442,
                "ROIC": -0.25415179
            },
            "ValuationRatios": {
                "MarketCap": 51814128927200.0,
                "BookValuePerShare": 30433.59705579,
                "BasicEPS": 2843.09875562,
                "PriceToBook": 2.29351791,
                "PriceToEarning": 24.55067727,
                "PriceToSales": 1.3011049,
                "EVtoEBITDA": -7.06284986,
                "PriceToCashFlow": -15.60598111
            },
            "Growth": {
                "NetRevenueGrowthYoY": -0.0065436,
                "EBTgrowthYoY": 0.17660793
            },
            "Revenue": 42669681559583.0,
            "AttributeToParentCompany": 2110496926600.0,
            "EBIT": -8040512078455.0
        },
        "ticker": "BVH",
        "year": 2024
    }
]
```


# Cấu hình file bat

**I.   Tạo file Batch**&#x20;

1. Mở Notepad.&#x20;

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FHN5XXky2fE7LZtyb0moy%2Fimage.png?alt=media&amp;token=f3bddc2a-d47d-4c20-8923-258ca9386e00" alt="" width="329"><figcaption></figcaption></figure>

2. Đánh đoạn code sau vào notepad:&#x20;

@echo off &#x20;

cd /d "C:\Path\To\Your\Python\Script" &#x20;

"C:\Path\To\Python\python.exe" script.py &#x20;

Exit&#x20;

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FbLhc8OaGkptuBVv4J0n1%2Fimage.png?alt=media&amp;token=3e571e0a-ff0e-415b-a523-16fd8a863f30" alt="" width="563"><figcaption></figcaption></figure>

* Thay "C:\Path\To\Your\Python\Script" bằng đường dẫn folder chứa file Python muốn chạy.&#x20;
* Thay "C:\Path\To\Python\python.exe" bằng đường dẫn đến file python.exe. Để tìm đường dẫn của file python.exe thực hiện nhấn Windows, tìm file gõ python.exe, nhấn chuột phải và chọn open file location.&#x20;

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FVIHm9DN5pvchsFfiXLIl%2Fimage.png?alt=media&amp;token=a5e2b567-a26a-4479-a9d2-f4fc6dc73519" alt="" width="563"><figcaption></figcaption></figure>

3. Lưu file theo cú pháp run\_script.bat (Đảm bảo là lựa chọn “All Files”)

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F3oqqM4tj5thIoBpL0GVV%2Fimage.png?alt=media&amp;token=62b5bc40-8c3a-4e9b-8542-065cfa4f17ff" alt=""><figcaption></figcaption></figure>

**II.   Đặt lịch bằng cách dùng Task Scheduler**&#x20;

1. Nhấn Win + R, đánh taskschd.msc và nhấn Enter.&#x20;

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2Fp0iHnxIZ8cXHMr5bXqJs%2Fimage.png?alt=media&amp;token=adca14f2-da55-4d5d-8d0f-37184031e63b" alt="" width="563"><figcaption></figcaption></figure>

2. Chọn Create Basis Task ở panel bên phải

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2Fph6Hx2YpAOWCiDHp1g1f%2Fimage.png?alt=media&amp;token=6b0731ba-10d8-4d61-aaf7-265018a5e625" alt="" width="563"><figcaption></figcaption></figure>

3. Đặt tên cho task (VD: “Run Python Script”) và ấn Next (Có thể thêm mô tả nếu muốn).

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F9ukxNiiA0cFgLbzmTeTt%2Fimage.png?alt=media&amp;token=55ba213b-d0b5-4aae-982d-aaabf8807d53" alt="" width="563"><figcaption></figcaption></figure>

4. Chọn tần suất Trigger (VD: Hằng ngày, hang tuần, hàng tháng, v.v.) và ấn Next

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FPSrRuSHlYtfNmfpSxzId%2Fimage.png?alt=media&amp;token=b1a3dc21-dda3-44b7-9e5f-e0a0533f5e50" alt="" width="563"><figcaption></figcaption></figure>

5. Đặt thời gian bắt đầu chạy vần ấn Next

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FNt8T0LtHYqMSpJu4EOcP%2Fimage.png?alt=media&amp;token=96711aff-941a-45dc-864d-b52b16779a28" alt="" width="563"><figcaption></figcaption></figure>

6. Chọn Start a Program và ấn Next

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F3sOeEgjC6uFmC2Mosnml%2Fimage.png?alt=media&amp;token=c05dd365-2574-4e2c-8a53-5115281c992d" alt="" width="563"><figcaption></figcaption></figure>

7. Chọn Browse và tìm file mà bạn muốn đặt lịch chạy (VD: run\_script.bat)

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FXdGff6dQhK6FVFYga3ke%2Fimage.png?alt=media&amp;token=c50731e8-06b6-4830-80f5-e31d5e36920a" alt="" width="563"><figcaption></figcaption></figure>

8. Chọn Finish và lưu tác vụ


# Các lỗi thường gặp

1. ### Lỗi ImportError

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FpPnREcIERLjJSa24u8fg%2Fimage.png?alt=media&amp;token=bcf56124-5223-4ee6-ba96-5cdf71f12048" alt=""><figcaption><p>Import Error</p></figcaption></figure>

**Nguyên nhân 11:**

Windows Defender có thể xóa hoặc cách ly file, vì vậy người dùng cần khôi phục nó trước khi chạy lại code.

Cách khôi phục file từ Quarantine:

1\. Mở Windows Security bằng cách nhấn Win + S, gõ “Windows Security”, rồi mở ứng dụng.

2\. Vào “Virus & threat protection”.

3\. Nhấp vào “Protection history”.

4\. Tìm mục “Threat quarantined” liên quan đến FiinQuant\\\_\_init\_\_.py.

5\. Nhấp vào “Actions” → Chọn “Restore”.

🔹 Lưu ý: Nếu Windows Defender tự động xóa file, bạn cần cài lại thư viện FiinQuant sau khi khôi phục.


# Giới thiệu

FiinQuantMCP - Đưa dữ liệu chứng khoán Việt Nam vào kỷ nguyên AI

**FiinQuant MCP** (Model Context Protocol) – giúp kết nối dữ liệu thị trường chứng khoán Việt Nam với các trợ lý AI như Claude, ChatGPT và các nền tảng AI hỗ trợ chuẩn MCP. Với FiinQuant MCP, người dùng có thể truy vấn dữ liệu thị trường bằng ngôn ngữ tự nhiên, thay vì phải xuất dữ liệu, xử lý Excel hoặc viết mã lập trình.

**FiinQuantMCP hiện hỗ trợ 20 công cụ bao gồm:**

<table><thead><tr><th width="195">Tên dữ liệu</th><th>Mô tả</th></tr></thead><tbody><tr><td>Dữ liệu Giao dịch</td><td>Giá OHLCV, khối lượng, giá trị giao dịch, mua bán chủ động, giao dịch NĐTNN từ khung thời gian intraday trở đi, chỉ số, hợp đồng tương lai và chứng quyền có bảo đảm của nhóm cổ phiếu, ngành, chỉ số.</td></tr><tr><td>Phân tích Kỹ thuật</td><td>RSI, MACD, EMA, SMA, ADX, Supertrend, MCDX… và hơn 100 chỉ báo kỹ thuật khác.</td></tr><tr><td>Dữ liệu Cơ bản</td><td>Báo cáo tài chính, chỉ số định giá P/E, P/B và tỷ số tài chính theo quý/năm.</td></tr><tr><td>Phân tích Dòng tiền</td><td>Thống kê mua/bán theo nhà đầu tư trong nước, nước ngoài và tự doanh; cổ phiếu đóng góp/kéo giảm chỉ số theo ngày.</td></tr><tr><td>Độ rộng Thị trường</td><td>Số cổ phiếu tăng/giảm/đứng giá trên VNINDEX và VN30; chỉ số sức mạnh tổng thể thị trường theo ngày, tuần, tháng.</td></tr><tr><td>Lọc Cổ phiếu</td><td>Stock Screener đa tiêu chí kết hợp kỹ thuật + cơ bản + dòng tiền, phân loại theo sàn giao dịch và ngành ICB.</td></tr><tr><td>Phân tích Tương đối</td><td>Relative Rotation Graph (RRG) so sánh hiệu suất cổ phiếu/ngành so với VNINDEX hoặc benchmark tùy chỉnh.</td></tr><tr><td>Tái cơ cấu Danh mục</td><td>Tính toán phân bổ vốn theo tỷ trọng VN30 hoặc các rổ chỉ số khác cho ngân sách đầu tư cụ thể.</td></tr></tbody></table>

Tham khảo thêm video hướng dẫn, thực hành FiinQuant tại: <https://www.youtube.com/watch?v=7zwZMs1dWbU&list=PLAFB5qkYRzFuPCSjXMB3EPN0Iv4PA-K2U>


# Danh sách các công cụ

FiinQuant MCP cung cấp các công cụ truy xuất, phân tích và xử lý dữ liệu thị trường chứng khoán Việt Nam, bao gồm dữ liệu giao dịch, định giá, tài chính doanh nghiệp, chỉ báo kỹ thuật, dòng tiền, phân ngành, sàng lọc cổ phiếu và các phân tích tùy chỉnh.

## 1. get\_trading\_data

Lấy dữ liệu giao dịch mới nhất hoặc lịch sử cho cổ phiếu, chỉ số thị trường, chỉ số ngành, hợp đồng tương lai hoặc chứng quyền có bảo đảm.

### Chi tiết

Tool này là nguồn chính để lấy giá giao dịch, bao gồm giá mở cửa, cao nhất, thấp nhất, đóng cửa, khối lượng và giá trị giao dịch. Có thể dùng để lấy giá mới nhất trong ngày hoặc chuỗi dữ liệu lịch sử theo ngày và intraday.

### Dữ liệu hỗ trợ

* Giá mở cửa, cao nhất, thấp nhất, đóng cửa
* Khối lượng giao dịch
* Giá trị giao dịch
* Dữ liệu mua/bán chủ động nếu có
* Dữ liệu nước ngoài mua, bán, ròng
* Dữ liệu theo ngày hoặc intraday: 1 phút, 5 phút, 15 phút, 30 phút, 1 giờ

### Prompt mẫu

* Giá đóng cửa mới nhất của FPT là bao nhiêu?
* Lấy dữ liệu OHLCV của HPG trong 30 phiên gần nhất.
* So sánh giá trị giao dịch của VNM và MWG trong tuần vừa rồi.
* Lấy dữ liệu intraday 5 phút của VNINDEX trong hôm nay.
* Diễn biến giá của SSI trong 3 tháng gần nhất như thế nào?

## 2. get\_basic\_info

Lấy thông tin cơ bản của doanh nghiệp niêm yết.

### Chi tiết

Tool này truy xuất các thông tin nhận diện doanh nghiệp như tên công ty, sàn niêm yết, ngành nghề và phân loại ICB.

### Dữ liệu hỗ trợ

* Mã cổ phiếu
* Tên công ty
* Sàn giao dịch
* Ngành
* Phân loại ICB
* Thông tin phân ngành theo cấp độ

### Prompt mẫu

* Cho tôi thông tin cơ bản của FPT.
* HPG thuộc ngành nào theo phân loại ICB?
* Lấy tên công ty, sàn niêm yết và ngành của VCB, BID, CTG.
* MWG đang được phân loại trong ngành nào?
* Danh sách thông tin cơ bản của các mã trong nhóm ngân hàng.

## 3. get\_equity\_snapshot

Lấy nhanh các chỉ tiêu thị trường phi tài chính tại một thời điểm cho danh sách cổ phiếu đã biết.

### Chi tiết

Tool này cung cấp snapshot về vốn hóa, tỷ lệ tự do chuyển nhượng, khối lượng lưu hành, room ngoại, beta và các chỉ tiêu giao dịch trung bình. Phù hợp khi cần lấy nhanh nhiều chỉ tiêu thị trường cho một danh sách mã cụ thể.

### Dữ liệu hỗ trợ

* Vốn hóa thị trường
* Giá đóng cửa snapshot
* Biến động giá 1 ngày, 1 tuần, 1 tháng, từ đầu năm
* Giá trị và khối lượng giao dịch trung bình
* Free float và free float ratio
* Số lượng cổ phiếu niêm yết/lưu hành
* Giao dịch nhà đầu tư nước ngoài
* Tỷ lệ sở hữu nước ngoài và room còn lại
* Beta, beta 6 tháng, beta 2 năm

### Prompt mẫu

* Lấy vốn hóa thị trường và beta của FPT, MWG, HPG.
* Room ngoại còn lại của VNM là bao nhiêu?
* So sánh free float ratio của VCB, BID và CTG.
* Cổ phiếu nào trong danh sách VN30 có vốn hóa lớn nhất?
* Lấy biến động giá 1 tháng và YTD của nhóm bán lẻ.

## 4. get\_financial\_statements

Lấy dữ liệu báo cáo tài chính của doanh nghiệp.

### Chi tiết

Tool này truy xuất dữ liệu báo cáo kết quả kinh doanh, bảng cân đối kế toán, lưu chuyển tiền tệ hoặc toàn bộ báo cáo tài chính theo năm và quý.

### Dữ liệu hỗ trợ

* Báo cáo kết quả kinh doanh
* Bảng cân đối kế toán
* Báo cáo lưu chuyển tiền tệ
* Doanh thu
* Lợi nhuận sau thuế
* Lợi nhuận sau thuế công ty mẹ
* EPS
* Dòng tiền từ hoạt động kinh doanh
* Các trường dữ liệu tài chính gốc từ FiinQuantX

### Prompt mẫu

* Doanh thu và lợi nhuận sau thuế của FPT trong Q1/2025 là bao nhiêu?
* Lấy báo cáo kết quả kinh doanh của HPG trong 5 năm gần nhất.
* So sánh lợi nhuận sau thuế của MWG năm 2024 và 2023.
* Dòng tiền hoạt động kinh doanh của VNM trong Q4/2024 là bao nhiêu?
* Lấy bảng cân đối kế toán của VCB trong các quý năm 2025.

## 5. get\_financial\_ratios

Lấy các chỉ số tài chính của doanh nghiệp.

### Chi tiết

Tool này truy xuất các chỉ số tài chính phổ biến theo năm hoặc quý, bao gồm khả năng sinh lời, hiệu quả hoạt động, đòn bẩy, định giá và các chỉ tiêu đặc thù ngành ngân hàng.

### Dữ liệu hỗ trợ

* ROE
* ROA
* EPS
* NIM
* CASA
* Tỷ lệ nợ xấu
* P/E
* P/B
* Các chỉ tiêu tài chính khác từ FiinQuantX

### Prompt mẫu

* ROE của FPT trong 5 năm gần nhất thay đổi như thế nào?
* So sánh ROA của VCB, BID và CTG trong năm 2024.
* NIM và CASA của TCB trong Q1/2025 là bao nhiêu?
* P/E hiện tại của MWG cao hay thấp so với các năm trước?
* Tỷ lệ nợ xấu của nhóm ngân hàng trong năm 2025 như thế nào?

## 6. get\_valuation\_metrics

Lấy dữ liệu định giá cho cổ phiếu, chỉ số hoặc ngành.

### Chi tiết

Tool này cung cấp các chỉ tiêu định giá theo phạm vi cổ phiếu, chỉ số hoặc ngành, hỗ trợ phân tích mức định giá hiện tại và lịch sử.

### Dữ liệu hỗ trợ

* Định giá cổ phiếu
* Định giá chỉ số
* Định giá ngành
* Dữ liệu lịch sử theo ngày
* Các chỉ tiêu như P/E, P/B hoặc các metric định giá khác tùy phạm vi dữ liệu

### Prompt mẫu

* Định giá P/E của VNINDEX hiện tại là bao nhiêu?
* So sánh P/B của VCB và BID trong 1 năm gần nhất.
* Ngành ngân hàng đang được định giá như thế nào?
* Lấy dữ liệu định giá của VN30 từ đầu năm đến nay.
* Cổ phiếu FPT đang giao dịch ở mức định giá nào so với lịch sử?

## 7. get\_market\_statistics

Lấy các thống kê thị trường cấp cổ phiếu.

### Chi tiết

Tool này dùng để truy xuất các thống kê thị trường như vốn hóa, giá trị giao dịch, khối lượng, dòng tiền nước ngoài, free float, dòng tiền theo nhóm nhà đầu tư, giao dịch tự doanh và dữ liệu trần/sàn.

### Dữ liệu hỗ trợ

* Vốn hóa thị trường
* Giá trị giao dịch
* Khối lượng giao dịch
* Dòng tiền nước ngoài
* Free float
* Dòng tiền theo nhóm nhà đầu tư
* Tự doanh
* Dữ liệu trần/sàn

### Prompt mẫu

* Lấy giá trị giao dịch của HPG trong 10 phiên gần nhất.
* Dòng tiền nước ngoài ở FPT trong tháng qua như thế nào?
* Thống kê khối lượng giao dịch của SSI từ đầu năm đến nay.
* Tự doanh mua bán ròng cổ phiếu nào trong danh sách ngân hàng?
* Vốn hóa thị trường của VNM thay đổi thế nào trong 6 tháng gần nhất?

## 8. get\_market\_breadth

Lấy dữ liệu độ rộng thị trường cho chỉ số.

### Chi tiết

Tool này cung cấp thống kê số mã tăng, giảm, đứng giá và các chỉ tiêu breadth cho một chỉ số như VNINDEX hoặc VN30.

### Dữ liệu hỗ trợ

* Số mã tăng
* Số mã giảm
* Số mã không đổi
* Độ rộng thị trường theo ngày, tuần, tháng, quý hoặc năm
* Dữ liệu breadth cho chỉ số

### Prompt mẫu

* Độ rộng thị trường VNINDEX hôm nay như thế nào?
* Có bao nhiêu mã tăng và giảm trong VN30 phiên gần nhất?
* So sánh breadth của VNINDEX trong tuần này và tuần trước.
* Thị trường có đang lan tỏa tích cực không?
* Lấy dữ liệu số mã tăng giảm của VNINDEX trong 1 tháng gần nhất.

## 9. get\_money\_flow\_contribution

Phân tích đóng góp hoặc tác động kéo giảm của cổ phiếu lên chỉ số.

### Chi tiết

Tool này dùng để xác định các cổ phiếu đóng góp tích cực hoặc tiêu cực vào diễn biến của một chỉ số, đồng thời hỗ trợ phân tích xếp hạng dòng tiền hoặc tác động theo nhiều khung thời gian.

### Dữ liệu hỗ trợ

* Top cổ phiếu đóng góp tăng điểm
* Top cổ phiếu kéo giảm chỉ số
* Phân tích theo 1 ngày, 5 ngày, 10 ngày, 20 ngày
* Xếp hạng theo chỉ số như VNINDEX, VN30

### Prompt mẫu

* Cổ phiếu nào kéo VNINDEX giảm mạnh nhất hôm nay?
* Top 10 mã đóng góp tích cực nhất cho VN30 trong 5 ngày qua.
* Những cổ phiếu nào đang tác động tiêu cực đến VNINDEX?
* So sánh nhóm cổ phiếu kéo tăng và kéo giảm thị trường trong 20 ngày gần nhất.
* Hôm nay chỉ số tăng chủ yếu nhờ những mã nào?

## 10. get\_index\_constituents

Lấy danh sách cổ phiếu thành phần của một chỉ số hoặc rổ cổ phiếu.

### Chi tiết

Tool này trả về danh sách mã thuộc một chỉ số như VN30 hoặc các rổ chỉ số được hỗ trợ.

### Dữ liệu hỗ trợ

* Danh sách cổ phiếu thành phần
* Mã cổ phiếu trong chỉ số
* Rổ chỉ số hoặc basket

### Prompt mẫu

* Danh sách cổ phiếu trong VN30 gồm những mã nào?
* Lấy các mã thành phần của VNFINLEAD.
* Cho tôi danh sách cổ phiếu trong chỉ số VNDIAMOND.
* Những mã nào đang thuộc rổ VN30?
* Lấy danh sách constituent để phân tích định giá nhóm VN30.

## 11. get\_icb\_industries

Lấy danh sách ngành theo hệ thống phân loại ICB.

### Chi tiết

Tool này trả về tên ngành theo cấp độ ICB, hỗ trợ phân tích theo ngành hoặc xây dựng bộ lọc ngành cho screener.

### Dữ liệu hỗ trợ

* Danh sách ngành ICB
* Phân ngành theo level
* Tên ngành và mã ngành tương ứng

### Prompt mẫu

* Lấy danh sách ngành ICB cấp 2.
* Có những ngành ICB level 4 nào trong hệ thống?
* Mã ngành của nhóm ngân hàng là gì?
* Cho tôi danh sách phân ngành để dùng cho bộ lọc cổ phiếu.
* Ngành chứng khoán thuộc ICB level nào?

## 12. screen\_stocks

Sàng lọc cổ phiếu theo bộ tiêu chí tài chính, định giá, thanh khoản, ngành và thị trường.

### Chi tiết

Tool này dùng để lọc và xếp hạng cổ phiếu dựa trên các chỉ tiêu từ FiinQuantX StockScreening. Có thể kết hợp nhiều điều kiện như P/E, P/B, ROE, tăng trưởng doanh thu, vốn hóa, thanh khoản, beta, room ngoại hoặc ngành.

### Dữ liệu hỗ trợ

* Bộ lọc định giá
* Bộ lọc tăng trưởng
* Bộ lọc khả năng sinh lời
* Bộ lọc thanh khoản
* Bộ lọc vốn hóa
* Bộ lọc ngành ICB
* Bộ lọc theo sàn giao dịch
* Sắp xếp kết quả theo chỉ tiêu mong muốn

### Prompt mẫu

* Tìm các cổ phiếu có P/E dưới 12 và ROE trên 15%.
* Sàng lọc cổ phiếu vốn hóa lớn, thanh khoản cao, tăng trưởng doanh thu dương.
* Tìm các cổ phiếu ngành chứng khoán có P/B thấp nhất.
* Lọc cổ phiếu HOSE có room ngoại còn lại trên 20%.
* Tìm top 20 cổ phiếu có ROE cao nhất trong nhóm VNINDEX.

## 13. get\_technical\_indicators

Tính toán các chỉ báo kỹ thuật cho cổ phiếu hoặc chỉ số.

### Chi tiết

Tool này tính toán các chỉ báo kỹ thuật phổ biến dựa trên dữ liệu giá, hỗ trợ phân tích xu hướng, động lượng, dòng tiền và tín hiệu giao dịch.

### Chỉ báo hỗ trợ

* RSI
* MACD
* SMA
* EMA
* ADX
* MFI
* Supertrend
* MCDX
* Các chỉ báo FiinIndicator khác

### Dữ liệu hỗ trợ

* Chỉ báo theo ngày
* Chỉ báo intraday
* Dữ liệu điều chỉnh hoặc không điều chỉnh
* Giá trị mới nhất hoặc chuỗi lịch sử

### Prompt mẫu

* RSI 14 ngày của FPT hiện tại là bao nhiêu?
* Tính MACD của VNINDEX trong 6 tháng gần nhất.
* Cổ phiếu HPG có đang vượt SMA 50 không?
* Lấy tín hiệu Supertrend của MWG.
* So sánh RSI của SSI, VND và HCM.

## 14. detect\_pattern

Phát hiện mẫu hình kỹ thuật hoặc mô hình giá.

### Chi tiết

Tool này gọi các phương pháp nhận diện mẫu hình kỹ thuật như doji, engulfing, trendline hoặc hỗ trợ/kháng cự.

### Mẫu hình hỗ trợ

* Doji
* Engulfing
* Trendline
* Support/resistance
* Các pattern kỹ thuật được đăng ký trong hệ thống

### Prompt mẫu

* FPT có xuất hiện nến Doji gần đây không?
* Kiểm tra mẫu hình engulfing của HPG trong 30 phiên gần nhất.
* Tính vùng hỗ trợ và kháng cự của VNINDEX.
* Phát hiện trendline của cổ phiếu MWG.
* Mã SSI có tín hiệu đảo chiều kỹ thuật nào không?

## 15. get\_realtime\_bid\_ask

Lấy snapshot giá mua/bán realtime giới hạn.

### Chi tiết

Tool này lấy dữ liệu bid/ask realtime trong phiên giao dịch. Phù hợp khi cần quan sát trạng thái sổ lệnh hiện tại hoặc mức giá chào mua/chào bán gần nhất.

### Dữ liệu hỗ trợ

* Giá bid
* Giá ask
* Khối lượng bid/ask nếu có
* Snapshot realtime theo số lượng event giới hạn

### Prompt mẫu

* Lấy giá bid/ask realtime của FPT.
* Sổ lệnh hiện tại của HPG như thế nào?
* Kiểm tra giá chào mua và chào bán của SSI.
* Bid/ask của VN30F1M hiện tại ra sao?
* Có dữ liệu realtime cho MWG không?

## 16. get\_rrg\_analysis

Phân tích Relative Rotation Graph cho danh sách cổ phiếu so với benchmark.

### Chi tiết

Tool này dùng để phân tích vị thế tương đối của các cổ phiếu so với chỉ số tham chiếu, hỗ trợ nhận diện nhóm dẫn dắt, cải thiện, suy yếu hoặc tụt hậu.

### Dữ liệu hỗ trợ

* Phân tích RRG
* Benchmark mặc định VNINDEX
* Danh sách cổ phiếu tùy chọn
* Tham số phân tích bổ sung

### Prompt mẫu

* Phân tích RRG của FPT, MWG, HPG so với VNINDEX.
* Nhóm ngân hàng đang ở quadrant nào trên RRG?
* Cổ phiếu nào trong VN30 đang dẫn dắt thị trường?
* So sánh sức mạnh tương đối của SSI, VND và HCM.
* Những mã nào đang chuyển từ lagging sang improving?

## 17. get\_rebalance

Tính toán phân bổ danh mục theo chỉ số với một ngân sách nhất định.

### Chi tiết

Tool này hỗ trợ tính toán allocation hoặc tái cân bằng danh mục theo một chỉ số, ví dụ VN30, dựa trên ngân sách đầu tư cụ thể.

### Dữ liệu hỗ trợ

* Chỉ số mục tiêu
* Ngân sách đầu tư
* Số lượng phân bổ theo mã
* Gợi ý tỷ trọng hoặc giá trị đầu tư theo constituent

### Prompt mẫu

* Với 1 tỷ đồng, phân bổ theo rổ VN30 như thế nào?
* Tính rebalance danh mục VN30 với ngân sách 500 triệu.
* Tôi muốn mô phỏng danh mục theo chỉ số VN30.
* Với 2 tỷ đồng, nên mua bao nhiêu mỗi mã trong VN30?
* Tính allocation theo rổ VNDIAMOND nếu có dữ liệu hỗ trợ.


# Hướng dẫn cài đặt


# Hướng dẫn cấu hình FiinQuant MCP Server trên Claude Desktop

## 1. Tải Claude Desktop

Truy cập trang chủ chính thức của Claude để tải về phiên bản Claude Desktop phù hợp với hệ điều hành đang sử dụng (Windows, macOS hoặc Linux).

* Mở trình duyệt web và truy cập địa chỉ: <https://claude.com/download>
* Chọn đúng phiên bản tương ứng với hệ điều hành của bạn (Windows / macOS / Linux).
* Tiến hành cài đặt theo hướng dẫn của trình cài đặt cho đến khi hoàn tất.

## 2. Mở cài đặt Connectors

Truy cập vào phần cài đặt connector của Claude Desktop:

* Mở **Settings** (Cài đặt) trong Claude Desktop.
* Điều hướng đến mục **Connectors**.
* Chọn **Customize** để mở danh sách connector tùy chỉnh.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FLSRXdxsbKwvoTRnXi3Yv%2Fimage.png?alt=media&amp;token=cf348946-837f-47de-8553-8dc1012d5816" alt=""><figcaption></figcaption></figure>

## 3. Thêm Custom Connector mới

Trong giao diện Customize, tiến hành thêm connector mới:

* Ấn vào nút dấu cộng **"+"** để mở menu thêm mới.
* Chọn **"Add custom connector"** để bắt đầu tạo connector tùy chỉnh.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FwTLc66ypQyfsZiZoUJcX%2Fimage.png?alt=media&amp;token=d410e66f-935a-4150-9a09-b3ae58c3023d" alt=""><figcaption></figcaption></figure>

## 4. Điền thông tin Connector

Nhập các thông tin sau vào biểu mẫu Add custom connector:

<table><thead><tr><th width="188">Thông số</th><th>Giá trị</th></tr></thead><tbody><tr><td>Name</td><td>FiinQuant MCP</td></tr><tr><td>URL</td><td><a href="https://fiinquant-mcp.fiingroup.vn/mcp">https://fiinquant-mcp.fiingroup.vn/mcp</a></td></tr><tr><td>ClientID</td><td>FiinQuant.Web.Front.Client</td></tr></tbody></table>

Sau khi điền xong, ấn nút **"Add"** để lưu connector.

{% hint style="info" %}
**Mẹo:** Hãy kiểm tra kỹ URL trước khi ấn Add — đảm bảo giao thức `https://` đầy đủ và không có khoảng trắng thừa trong trường nhập liệu.
{% endhint %}

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F2vRs7I9JMKCB1CFJGoLt%2Fimage.png?alt=media&amp;token=4ad174ce-fc97-4469-a4b2-093994911ff9" alt=""><figcaption></figcaption></figure>

## 5. Kết nối với FiinQuant

Sau khi connector được thêm thành công:

* Ấn nút **"Connect"** bên cạnh connector vừa tạo.
* Hệ thống sẽ tự động **redirect** (chuyển hướng) sang trang **FiinQuant Authentication** để thực hiện xác thực.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FIP5n8gwRjPG4ci6t3FzY%2Fimage.png?alt=media&amp;token=dfaa9f98-4f57-4e64-8c6a-adb3bb3ead0f" alt=""><figcaption></figcaption></figure>

> ***Lưu ý:** Trang FiinQuant Authentication sẽ mở trong trình duyệt mặc định. Nếu không thấy trang xuất hiện, hãy kiểm tra xem trình duyệt có chặn pop-up không và cho phép trang hiển thị.*

## 6. Đăng nhập tài khoản FiinQuant

Tại trang FiinQuant Authentication, thực hiện đăng nhập:

* Điền **tài khoản** (username/email) đã được đăng ký với FiinQuant.
* Điền **mật khẩu** tương ứng.
* Ấn **Đăng nhập** để hoàn tất xác thực.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F3nrUcmcsbEnKxNKatjZ4%2Fimage.png?alt=media&amp;token=68bda555-6481-4c2a-b224-bcf2dc63d12a" alt=""><figcaption></figcaption></figure>

## 7. Kích hoạt MCP trong conversation

Sau khi Claude Desktop khởi động lại, cần kích hoạt connector trong cuộc hội thoại:

* Tạo một **conversation mới**.
* Ở thanh chat phía dưới, ấn vào nút dấu cộng **"+"** để mở menu các công cụ.
* Chọn **Connectors**.
* Đảm bảo **FiinQuant MCP** được **toggle on** (bật).

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FgsMTUNOFsvfQOseiGeo9%2Fimage.png?alt=media&amp;token=f8013145-fbab-411a-a18d-05e2afd5d243" alt=""><figcaption></figcaption></figure>


# Hướng dẫn cài đặt FiinQuant MCP Server trên ChatGPT

## 1. Bật chế độ nhà phát triển

Truy cập vào phần cài đặt ứng dụng của ChatGPT để bật chế độ nhà phát triển:

* Mở **Settings** (Cài đặt) trong ChatGPT.
* Vào mục **Plugins**.
* Bật **Developer mode** (Chế độ nhà phát triển).

> ***Lưu ý:** Chế độ nhà phát triển cho phép tạo và quản lý các MCP server tùy chỉnh. Nếu không bật, bạn sẽ không thấy tùy chọn tạo ứng dụng mới ở bước tiếp theo.*

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2F4W1phKi9I1JypErgRUih%2Fimage.png?alt=media&amp;token=a7dae030-160c-43ab-bfae-5605c7c170ef" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FBi4OeftbiaftvnNpsNTY%2Fimage.png?alt=media&amp;token=3218a25c-82da-46d9-8f54-2d5e07ebcbb4" alt=""><figcaption></figcaption></figure>

## 2. Tạo Plugin mới

Sau khi đã bật chế độ nhà phát triển:

* Quay lại tab **Plugins** -> Chọn **Browse plugins**
* Ấn nút **dấu cộng** trên góc trên bên phải để thêm MCP

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FZxLcrfpdobtW5YbkyDW4%2Fimage.png?alt=media&amp;token=f84a9a3f-e217-4447-bf22-a0fcadb7ea00" alt=""><figcaption></figcaption></figure>

## 3. Điền thông tin MCP Server

Điền đầy đủ các thông tin sau vào biểu mẫu tạo ứng dụng:

<table><thead><tr><th width="197">Thông số</th><th>Giá trị</th></tr></thead><tbody><tr><td>Name</td><td>FiinQuant MCP</td></tr><tr><td>Connection</td><td>Server URL (URL máy chủ)</td></tr><tr><td>URL</td><td><a href="https://fiinquant-mcp.fiingroup.vn/mcp">https://fiinquant-mcp.fiingroup.vn/mcp</a></td></tr><tr><td>Authentication</td><td>Chọn Advanced OAuth settings</td></tr><tr><td>Registration method (Mục Client Registration)</td><td>User-Defined OAuth Client</td></tr><tr><td>OAuth Client ID (Mục Callback URL)</td><td>FiinQuant.Web.Front.Client</td></tr><tr><td>Token endpoint auth method (Mục Callback URL)</td><td>None</td></tr></tbody></table>

* Tick vào ô **"I understand and want to continue"** để xác nhận rằng bạn đồng ý với các điều khoản sử dụng.
* Ấn nút **"Create"** để hoàn tất việc tạo MCP.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2Fuex26erN3iv1Y6TbMteF%2Fimage.png?alt=media&amp;token=4cfa0b85-2a90-4b1f-a0f0-bd98d40cb58c" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**Mẹo:** Hãy kiểm tra kỹ URL trước khi ấn Tạo — đảm bảo giao thức `https://` đầy đủ và không có khoảng trắng thừa.
{% endhint %}

## 4. Đăng nhập qua OAuth

Sau khi ấn **"Create"**, màn hình sẽ pop up thông báo đăng nhập, chọn **"Sign in with FiinQuant MCP"** trong cửa sổ pop up.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FLg2ut4iC7zTr8A3jS7Pb%2Fimage.png?alt=media&amp;token=b86e73b2-2c7a-4d1c-b1cb-385983b4d186" alt=""><figcaption></figcaption></figure>

## 5. Xác thực với FiinQuant

Hệ thống sẽ tự động chuyển hướng (redirect) sang trang **FiinQuant Authentication**:

* Điền **tài khoản** và **mật khẩu** đã được đăng ký với FiinQuant.
* Ấn **Đăng nhập** để hoàn tất xác thực.

> ***Lưu ý:** Sau khi đăng nhập thành công, hệ thống sẽ tự động chuyển bạn về ChatGPT và MCP server sẽ sẵn sàng để sử dụng.*

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FVpOQVbG0lkZ5JHLukCQD%2Fimage.png?alt=media&amp;token=ba358df2-7194-49da-b92c-5c9296dedd64" alt=""><figcaption></figcaption></figure>

## 6. Cách sử dụng MCP trong ChatGPT

Sau khi cấu hình hoàn tất, tiến hành sử dụng FiinQuant MCP trong các cuộc hội thoại:

* Tạo một **conversation mới** trong ChatGPT.
* Ở thanh nhập liệu phía dưới, bấm vào nút dấu cộng **"+"**.
* Chọn **"Add"** (Thêm).
* Chọn **FiinQuant MCP** từ danh sách các connector.
* Sau khi được thêm, bạn có thể đặt câu hỏi liên quan đến dữ liệu tài chính và ChatGPT sẽ sử dụng FiinQuant MCP để truy xuất thông tin.

<figure><img src="https://3318188420-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fkme4XYjWbuM3iRJzUu9r%2Fuploads%2FAH8vIjFvTUCSkzrwcn6n%2Fimage.png?alt=media&amp;token=0e1806bb-6834-4dbc-8b90-ba3ef289bdd2" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**Mẹo sử dụng:** MCP cần được thêm vào từng conversation mới. Nếu cuộc hội thoại không phản hồi dữ liệu tài chính, hãy kiểm tra lại xem FiinQuant MCP đã được thêm vào conversation hiện tại chưa.
{% endhint %}


# Overview

**FiinQuant – A data library and analytic tool for Python**

### <mark style="color:purple;">What is FiinQuant?</mark>

FiinQuant is a data library and analytic tool for **Python**, enabling investors, analysts, and developers to easily access, process, and accurately analyze financial data quickly and precisely.

<figure><img src="https://822650840-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fh9puEqHZfqYUzc1yRE8w%2Fuploads%2FRkv96IsqkBi1EeBTBSvR%2Fimage.png?alt=media&amp;token=35248dc5-5d0f-4447-bed6-499a2ac8ac0e" alt=""><figcaption></figcaption></figure>

Key features of FiinQuant include:

* **Historical data retrieval:** Allows access to and retrieval of data from financial data providers.
* **Real-time order matching data retrieval:** Provides the ability to receive real-time data, helping to monitor the market and continuously update information.
* **Historical data and real-time data connection:** The library allows calling methods to connect historical data from a specific time with real-time data across various timeframes.
* **Technical indicator creation:** Offers tools to build and calculate technical indicators ranging from simple ones like moving averages (SMA, EMA, etc.) to more complex ones such as RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Ichimoku, and many other indicators.

With its ability to combine data collection, real-time processing, and indicator analysis, **FiinQuant** is a comprehensive solution for financial professionals and investors to conduct market research, thereby supporting effective investment decisions.


# Key highlights

### <mark style="color:purple;">Authoritative trading data</mark>

FiinQuant directly integrates real-time market data from exchanges (HOSE, HNX, UPCOM), ensuring accuracy, transparency, and reliability for analysis, trading, and research applications.

### <mark style="color:purple;">Real-time WebSocket connection</mark>

FiinQuant supports stable and high-performance WebSocket connections, enabling:

* Receiving tick-by-tick data or updates in batches (e.g., 1s, 5s, 1min)
* Automatically pushing data to dashboards, bots, and alert systems
* Continuous synchronization with historical data to support complex systems

WebSocket is integrated for both price and order book modules.

### <mark style="color:purple;">Minute-level aggregated data</mark>

The system supports tick-by-tick data down to minute-level, with full timeframes of 1', 5', 15', 1h, 4h, and 1D, allowing users to call data directly without needing to maintain their own server systems for historical data storage.

### <mark style="color:purple;">Readiness for combining historical and real-time data</mark>

FiinQuant provides built-in functions for merging and synchronizing historical and real-time data, which makes strategy development, model backtesting, and trading deployment easier and smoother.

### <mark style="color:purple;">Smart cash flow data – real-time & historical</mark>

Includes proactive indicators such as:

* **BU-SD:** Net buy/sell value of institutional/proactive investors.
* **Foreign Investors:** Real-time and time-series activities of foreign investors.

This is useful for identifying significant capital flows and short-to-medium term market trends.

### <mark style="color:purple;">**Integration of popular technical analysis (TA) indicators**</mark>

The library comes with integrated indicator sets such as:

* MA, EMA, RSI, MACD, Bollinger Bands
* Breakout Signals, Divergence
* Volume Profile and other market behavior indicator groups

### <mark style="color:purple;">**Advanced financial functions for professional investors**</mark>

FiinQuant provides many utility functions ready for deployment:

* **Stock prediction:** Forecast stock price trends using ML (Machine Learning)
* **Similar chart:** Search for stocks with similar chart patterns
* **Rebalance index:** Rebalance index portfolios periodically or based on signals
* **Factor models:** Analyze factors influencing stock performance
* Continuously update other financial models periodically

> **Using the FiinQuant library is not merely about data retrieval; it's about utilizing an ecosystem of built-in quantitative tools designed for investors.**




---

[Next Page](/llms-full.txt/1)

