Vnstock Logo

Kiến trúc thư viện

Mở rộngvnstock_data v4.0.6

Mục lục

Gợi ý
Thư viện vnstock_data được thiết kế với cấu trúc dạng mô-đun, dễ mở rộng, dễ tích hợp, và dễ chuyển đổi nguồn dữ liệu chỉ qua một tham số cấu hình.

Đây là bộ công cụ Python chạy trên máy của bạn, giúp bạn kết nối và chuẩn hoá dữ liệu chứng khoán, kinh tế vĩ mô, hàng hoá từ nguồn bên thứ ba để xây dựng quy trình phân tích, nghiên cứu và dự báo thị trường của riêng mình.

Triết Lý Thiết Kế 3 Lớp

Mọi dòng code trong vnstock_data đều hướng tới một mục tiêu duy nhất: Giúp bạn tập trung vào phân tích tài chính thay vì xử lý mã nguồn.

Cả ba lớp dưới đây đều chạy trong môi trường Python trên thiết bị hoặc máy chủ do bạn kiểm soát. Truy vấn đi thẳng từ đó tới nguồn bên thứ ba, không qua máy chủ trung chuyển của Vnstock; Vnstock không vận hành kho dữ liệu thị trường để bán lại.

Lớp Kiến TrúcBản Chất Kỹ ThuậtÝ nghĩa
Giao diện hợp nhất (Unified UI)Lớp trên cùng, tổ chức lại toàn bộ dữ liệu thành cấu trúc nghiệp vụ (Market, Reference, Fundamental...).Lập trình như một chuyên gia tài chính: Trải nghiệm xuyên suốt, dễ tìm kiếm chức năng qua show_api(), gọi hàm liền mạch qua dấu chấm . để phân nhánh hàm mà không cần quan tâm tới cài đặt nguồn dữ liệu.
Giao tiếp chung (Core Adapter)Lớp trung gian tạo ra một chuẩn giao tiếp duy nhất giữa code của bạn và các nguồn được hỗ trợ.Tự do chuyển đổi nguồn dữ liệu: Đổi nguồn (từ VCI sang VND, MAS) chỉ đơn giản là thay đổi giá trị source= khi khởi tạo class. Code được hạn chế tối đa khả năng lỗi, tăng tính bền vững và linh hoạt cho dự án.
Module Nguồn cấp (Implementation)Lớp dưới cùng gồm các kết nối chạy trên máy của bạn, mỗi luồng kết nối tới một nguồn và chuyển phản hồi về cấu trúc chung.Quyền kiểm soát chi tiết: Cho phép người dùng có kinh nghiệm có thể khai thác tối đa các chức năng của thư viện được đặt sâu trong mã nguồn.

Hướng Dẫn Sử Dụng

Thông báo tương thích

vnstock_data hỗ trợ 3 cách tiếp cận khi gọi dữ liệu, được tổ chức theo cấu trúc 3 lớp. Người dùng đang dùng bản Cộng đồng của Vnstock có thể chuyển sang mượt mà chỉ bằng cách thay đổi câu lệnh import. Để tận dụng toàn bộ sức mạnh và tiện ích mới nhất, Vnstock giới thiệu Unified UI là cách gọi lệnh mặc định.

Python
# Câu lệnh cũ
from vnstock import Market, Reference, Fundamental

# Câu lệnh dùng cho bản Mở rộng (Đổi tên thư viện là được)
from vnstock_data import Market, Reference, Fundamental

1. Giao diện hợp nhất (Unified UI - Mặc định)

Kiến trúc tiêu chuẩn mới nhất, vận hành mượt mà, cảm hứng thiết kế từ cơ chế phân loại của Bloomberg Terminal, FIX.

Đây là cách tương tác với dữ liệu theo các miền nghiệp vụ rõ ràng, giúp lập trình viên thao tác một cách tự nhiên mà không cần bận tâm về cấu trúc kỹ thuật bên dưới.

Python
from vnstock_data import Market, Reference, Fundamental

# Ví dụ tra cứu giá lịch sử thông qua Market Layer
df = Market.quote(symbol="VCI") \
           .history(start="2024-02-01", end="2025-04-18", interval="1D")

Ưu điểm:

  • Trải nghiệm lập trình liền mạch với khả năng gọi chuỗi lệnh (method chaining).
  • Các nhóm dữ liệu được tổ chức logic theo sát kiến thức tài chính.
  • Hỗ trợ hàm show_api() để dễ dàng tự khám phá chức năng mà không cần mở tài liệu từ website để tra cứu.

2. Sử dụng cổng Giao tiếp chung (Core Adapter)

Tối ưu cho sự linh hoạt, hoán đổi nguồn dữ liệu, phù hợp người dùng chuyển từ bản cũ.

Phương thức này dành riêng cho người dùng quen thuộc với phong cách của phiên bản Vnstock trước đây. Chỉ cần điều chỉnh phần nạp thư viện, gần như toàn bộ tính năng và code hiện tại của bạn sẽ tiếp tục hoạt động nguyên vẹn.

Python
from vnstock_data import Quote, Trading, Finance, Listing, Company, Macro

quote = Quote(source="vci", symbol="VCI")
df = quote.history(start="2024-02-01", end="2025-04-18", interval="1D")

Ưu điểm:

  • Chuyển đổi nhanh chóng từ bản Cộng đồng.
  • Linh hoạt đối chiếu và thay đổi nguồn (từ VCI sang VND, MAS...).

3. Sử dụng trực tiếp Module Nguồn cấp

Kiểm soát chặt chẽ nhất, tối ưu cho sự ổn định ở môi trường triển khai sản phẩm.

Thay vì dùng giao tiếp chung, bạn gọi thẳng module connector riêng của từng nguồn.

Python
from vnstock_data.explorer.vci import Quote

quote = Quote(symbol="VCI")
df = quote.history(start="2024-02-01", end="2025-04-18", interval="1D")

Ưu điểm:

  • Giảm thiểu hoàn toàn rủi ro chức năng không hỗ trợ chéo.
  • Truy cập vào những trường dữ liệu đặc thù chỉ có ở một nguồn cụ thể.

Tra cứu API

Thay vì phải tra cứu tài liệu rời rạc, Unified UI gom toàn bộ thư viện lại thành một cây tính năng. Nhập show_api() và bạn sẽ có toàn cảnh bức tranh dữ liệu.

Python
from vnstock_data import show_api, show_doc
>>> show_api()
Hiển thị kết quả API Tree
Text
API STRUCTURE TREE - VNSTOCK_DATA (Unified UI Endpoints)
vnstock_data
├── Reference
│   ├── bond # Access bond reference data.
│   │   ├── list() # List bonds available in the market.
│   ├── company() # Access company-specific reference data.
│   │   ├── events() [VCI] -> DataFrame # Get company events.
│   │   ├── info() [VCI] -> DataFrame # Get company info/overview.
│   │   ├── margin_ratio() [KBS] -> DataFrame # Get margin lending ratio for the company across brokers.
│   │   ├── news() [VCI] -> DataFrame # Get company news.
│   │   ├── officers() [VCI] -> DataFrame # Get company officers.
│   │   ├── shareholders() [VCI] -> DataFrame # Get company shareholders.
│   │   ├── subsidiaries() [VCI] -> DataFrame # Get company subsidiaries.
│   ├── equity # Access equity reference data.
│   │   ├── list() [VCI] -> DataFrame # List all equity symbols.
│   │   ├── list_by_exchange() -> DataFrame # List all equities organized by exchange.
│   │   ├── list_by_group() -> DataFrame # List equities by group (e.g., VN30, HOSE).
│   │   ├── list_by_industry() -> DataFrame # List equities by industry (ICB classification).
│   ├── etf # Access ETF reference data.
│   │   ├── list() [KBS] -> DataFrame # List all Exchange-Traded Funds (ETFs) available in the market.
│   ├── events # Access events reference data (calendar, etc.).
│   │   ├── calendar() [VCI] -> DataFrame # Retrieve events calendar (dividends, AGM, new listings, ...) from the default data source.
│   │   ├── market() -> DataFrame # Retrieve special stock market events (holidays, system incidents, ...)
│   ├── futures() # Access index futures reference data (listing or symbol-specific info).
│   │   ├── info() [KBS] -> DataFrame # Get info and latest intraday information for the specific index future.
│   │   ├── list() [VCI] -> DataFrame # List all available futures indices with metadata.
│   ├── index # Access index reference data.
│   │   ├── groups() [KBS] -> DataFrame # List all supported index groups and categories.
│   │   ├── list() [KBS] -> DataFrame # List all standardized market indices with metadata.
│   │   ├── list_by_group() -> DataFrame # List market indices by group/category.
│   │   ├── members() [KBS] -> Series # List constituents/members of the specified index.
│   ├── industry # Access industry reference data.
│   │   ├── list() [VCI] -> DataFrame # List ICB industry classifications for all symbols in the market.
│   │   ├── sectors() [VCI] -> DataFrame # List all symbols by their industry sectors.
│   ├── market # Access current market status.
│   │   ├── status() [MAS] -> DataFrame # Retrieve current stock market status (OPEN, CLOSED, ATO, ATC, etc.)
│   ├── search # Access global symbol search.
│   │   ├── symbol() [MSN] -> DataFrame # Retrieves a list of symbols from the market matching the query.
│   └── warrant() # Access covered warrant reference data (info, specifications, pricing).
│       ├── info() [KBS] -> DataFrame # Get info and latest intraday information for the specific covered warrant.
│       ├── list() [VCI] -> DataFrame # List all available covered warrants.
├── Market
│   ├── commodity() # Access commodity market data (e.g., 'GC=F').
│   │   ├── ohlcv() [MSN] -> DataFrame # Historical OHLCV bars.
│   │   ├── quote() -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│   │   ├── summary() -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│   ├── crypto() # Access crypto market data (e.g., 'BTC').
│   │   ├── ohlcv() [MSN] -> DataFrame # Historical OHLCV bars.
│   │   ├── quote() -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│   │   ├── summary() -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│   ├── equity() # Access equity market data.
│   │   ├── block_trades() [KBS] -> DataFrame # Intraday or historical data for negotiated/block trades (giao dịch thoả thuận).
│   │   ├── foreign_flow() [VCI] -> DataFrame # Historical or daily foreign buy/sell volume and value.
│   │   ├── odd_lot() [KBS] -> DataFrame # Intraday pricing or trades for odd-lot execution (Lô lẻ).
│   │   ├── ohlcv() [KBS] -> DataFrame # Historical OHLCV bars.
│   │   ├── order_book() [KBS] -> DataFrame # Order book levels (Best Bid/Ask L2/L3).
│   │   ├── proprietary_flow() [VCI] -> DataFrame # Trade data for proprietary desks (Tự doanh).
│   │   ├── quote() [KBS] -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│   │   ├── session_stats() [VCI] -> DataFrame # End-of-session aggregate statistics.
│   │   ├── summary() [KBS] -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│   │   ├── trade_history() [KBS] -> DataFrame # Historical trading statistics (price, volume, value) for Equities.
│   │   ├── trades() [KBS] -> DataFrame # Intraday tick-by-tick trading tape (Time & Sales).
│   │   ├── volume_profile() [KBS] -> DataFrame # Aggregated volume distributed across executed price levels (Volume Profile).
│   ├── etf() # Access ETF market data.
│   │   ├── ohlcv() [KBS] -> DataFrame # Historical OHLCV bars.
│   │   ├── order_book() [KBS] -> DataFrame # Order book levels (Best Bid/Ask L2/L3).
│   │   ├── quote() [KBS] -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│   │   ├── session_stats() [VCI] -> DataFrame # End-of-session aggregate statistics.
│   │   ├── summary() [KBS] -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│   │   ├── trades() [KBS] -> DataFrame # Intraday tick-by-tick trading tape (Time & Sales).
│   ├── forex() # Access forex market data (e.g., 'USDVND').
│   │   ├── ohlcv() [MSN] -> DataFrame # Historical OHLCV bars.
│   │   ├── quote() -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│   │   ├── summary() -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│   ├── futures() # Access futures market data.
│   │   ├── ohlcv() [KBS] -> DataFrame # Historical OHLCV bars.
│   │   ├── order_book() [KBS] -> DataFrame # Order book levels (Best Bid/Ask L2/L3).
│   │   ├── quote() [KBS] -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│   │   ├── summary() [KBS] -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│   │   ├── trades() [KBS] -> DataFrame # Intraday tick-by-tick trading tape (Time & Sales).
│   ├── index() # Access index market data.
│   │   ├── ohlcv() [KBS] -> DataFrame # Historical OHLCV bars.
│   │   ├── quote() [KBS] -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│   │   ├── summary() [KBS] -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│   └── warrant() # Access warrant market data.
│       ├── ohlcv() [KBS] -> DataFrame # Historical OHLCV bars.
│       ├── order_book() [KBS] -> DataFrame # Order book levels (Best Bid/Ask L2/L3).
│       ├── quote() [KBS] -> DataFrame # Latest single-symbol pricing snapshot (subject to source delay).
│       ├── summary() [KBS] -> DataFrame # Stock Info / Snapshot summary metrics including pricing,
│       ├── trades() [KBS] -> DataFrame # Intraday tick-by-tick trading tape (Time & Sales).
├── Fundamental
│   └── equity() # Access financial data for a specific corporate equity (Fundamental Layer).
│       ├── balance_sheet() [KBS] -> DataFrame # Extracts Balance Sheet.
│       ├── cash_flow() [KBS] -> DataFrame # Extracts Cash Flow statement.
│       ├── income_statement() [KBS] -> DataFrame # Extracts Income Statement.
│       ├── note() [VCI] -> DataFrame # Extracts Footnotes (Thuyết minh Báo cáo tài chính).
│       ├── ratio() [KBS] -> DataFrame # Extracts key financial ratios (P/E, ROE, Debt/Equity, etc.).
├── Analytics
│   └── valuation() # Access historical valuation multiples for market indices (Analytics Layer).
│       ├── evaluation() [VND] -> DataFrame # Retrieves an overview of the market with both P/E and P/B ratios.
│       ├── pb() [VND] -> DataFrame # Retrieves P/B (Price-to-Book) ratio data.
│       ├── pe() [VND] -> DataFrame # Retrieves P/E (Price-to-Earnings) ratio data.
├── Macro
│   ├── commodity() # Access global commodity prices (Macro Layer - Commodity Domain).
│   │   ├── coke() [ASEAN] -> DataFrame # Coke (Coal) prices.
│   │   ├── corn() [ASEAN] -> DataFrame # Corn prices.
│   │   ├── gas() -> DataFrame # Gas prices. 'GLOBAL' returns natural gas futures.
│   │   ├── gold() -> DataFrame # Gold prices. 'GLOBAL' for world gold.
│   │   ├── iron_ore() [ASEAN] -> DataFrame # Iron ore prices.
│   │   ├── oil_crude() [ASEAN] -> DataFrame # Crude Oil prices.
│   │   ├── soybean() [ASEAN] -> DataFrame # Soybean prices.
│   │   ├── steel() -> DataFrame # Steel prices. 'GLOBAL' for HRC1!.
│   │   ├── sugar() [ASEAN] -> DataFrame # Sugar prices.
│   ├── currency() # Access foreign exchange rates (Macro Layer - Currency Domain).
│   │   ├── exchange_rate() [ASEAN] -> DataFrame # Foreign exchange rates.
│   └── economy() # Access standard macroeconomic indicators (Macro Layer - Economy Domain).
│       ├── cpi() [ASEAN] -> DataFrame # Consumer Price Index data.
│       ├── fdi() [ASEAN] -> DataFrame # Foreign Direct Investment data.
│       ├── gdp() [ASEAN] -> DataFrame # GDP data.
│       ├── import_export() [ASEAN] -> DataFrame # Import/Export macro data.
│       ├── money_supply() [ASEAN] -> DataFrame # Money supply data.
└── Insights
    ├── ranking() # Access market ranking metrics - Top movers by various criteria (Insights Layer).
    │   ├── deal() [VND] -> DataFrame # Top 10 stocks with highest put-through/deal volume spikes.
    │   ├── foreign_buy() [VND] -> DataFrame # Top 10 stocks with highest foreign net buy value.
    │   ├── foreign_sell() [VND] -> DataFrame # Top 10 stocks with highest foreign net sell value.
    │   ├── gainer() [VND] -> DataFrame # Top 10 stocks with highest price increase.
    │   ├── loser() [VND] -> DataFrame # Top 10 stocks with highest price decrease.
    │   ├── value() [VND] -> DataFrame # Top 10 stocks with highest trading value.
    │   ├── volume() [VND] -> DataFrame # Top 10 stocks with highest volume spikes.
    └── screener() # Access stock screener functionality (Insights Layer).
        ├── criteria() [VCI] -> DataFrame # Retrieves the mapping list of criteria to explain field names (data columns).
        ├── filter() [VCI] -> DataFrame # Retrieves full market data (all stocks) with all available criteria (ratios, metrics)

Tip: Sử dụng show_doc(node) để đọc docstring.
[Navigation] = Intermediate methods returning domain objects