{"id":"85f07fd5-b2a6-458c-860f-cc0c16732f9c","entityType":"agent","slug":"clawhub-teahann-vnstock-free-expert","name":"Vnstock Free Expert","canonicalUrl":"https://www.xpersona.co/agent/clawhub-teahann-vnstock-free-expert","canonicalPath":"/agent/clawhub-teahann-vnstock-free-expert","generatedAt":"2026-10-10T07:55:12.987Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-10T00:25:58.054Z","emptyReason":null},"description":"Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users r... Skill: Vnstock Free Expert Owner: teahann Summary: Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users r... Tags: latest:1.0.3 Version history: v1.0.3 | 2026-05-22T00:22:16.119Z | user Update Vietnam institutional stock skill system with D1 governance, trade decision policy, and harness agent guide. v1.0.2 | 2026-0","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.8K downloads reported by the source. Last updated 10/10/2026.","installCommand":"clawhub skill install s172d4r9d0h6bvvd3mpq517yrn861np5:vnstock-free-expert","sourceUrl":"https://clawhub.ai/teahann/vnstock-free-expert","homepage":"https://clawhub.ai/teahann/skills/vnstock-free-expert","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/teahann/vnstock-free-expert","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/teahann/skills/vnstock-free-expert","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":65,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users r..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-10T00:25:58.054Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T00:25:58.054Z","emptyReason":null},"stars":null,"forks":null,"downloads":1839,"packageName":null,"latestVersion":"1.0.3","tractionLabel":"1.8K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T00:25:58.053Z","emptyReason":null},"lastUpdatedAt":"2026-10-10T00:25:58.054Z","lastCrawledAt":"2026-10-10T00:25:58.053Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-11T00:25:58.053Z","lastVerifiedAt":null,"highlights":[{"version":"1.0.3","createdAt":"2026-05-22T00:22:16.119Z","changelog":"Update Vietnam institutional stock skill system with D1 governance, trade decision policy, and harness agent guide.","fileCount":29,"zipByteSize":78801},{"version":"1.0.2","createdAt":"2026-02-25T01:20:03.105Z","changelog":"vnstock-free-expert 1.0.2 - Minor update to agent configuration (agents/openai.yaml) with no changes to skill logic or documentation. - No changes to usage, API, scripts, or user-facing behavior.","fileCount":28,"zipByteSize":76988},{"version":"1.0.1","createdAt":"2026-02-24T15:58:37.484Z","changelog":"- Added a required downstream handoff bundle specification for single-ticker or small-list deep dives, enabling output as a compact JSON for reuse by other skills. - No changes to workflow, interface, or main script behavior. - Documentation updated to describe JSON bundle contents and use cases for cross-skill integration.","fileCount":28,"zipByteSize":76988},{"version":"1.0.0","createdAt":"2026-02-23T10:15:01.988Z","changelog":"- Initial release of vnstock-free-expert for advanced, free-tier-safe Vietnam stock analysis. - Implements strict rate-limit control and caching to stay within API free-tier constraints. - Provides a complete end-to-end pipeline: universe building, data collection, scoring, report generation. - Uses kbs as primary data source, with vci fallback; excludes tcbs; disables Screener API by default. - Enforces required confidence rubric and clear reporting of coverage, risks, and missing data. - Includes generic method invocation scripts for broader vnstock package access.","fileCount":28,"zipByteSize":76709}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s172d4r9d0h6bvvd3mpq517yrn861np5:vnstock-free-expert","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T07:55:12.985Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-teahann-vnstock-free-expert/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-10T00:25:58.054Z","emptyReason":null},"readme":"Skill: Vnstock Free Expert\n\nOwner: teahann\n\nSummary: Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users r...\n\nTags: latest:1.0.3\n\nVersion history:\n\nv1.0.3 | 2026-05-22T00:22:16.119Z | user\n\nUpdate Vietnam institutional stock skill system with D1 governance, trade decision policy, and harness agent guide.\n\nv1.0.2 | 2026-02-25T01:20:03.105Z | auto\n\nvnstock-free-expert 1.0.2\n\n- Minor update to agent configuration (agents/openai.yaml) with no changes to skill logic or documentation.\n- No changes to usage, API, scripts, or user-facing behavior.\n\nv1.0.1 | 2026-02-24T15:58:37.484Z | auto\n\n- Added a required downstream handoff bundle specification for single-ticker or small-list deep dives, enabling output as a compact JSON for reuse by other skills.\n- No changes to workflow, interface, or main script behavior.\n- Documentation updated to describe JSON bundle contents and use cases for cross-skill integration.\n\nv1.0.0 | 2026-02-23T10:15:01.988Z | auto\n\n- Initial release of vnstock-free-expert for advanced, free-tier-safe Vietnam stock analysis.\n- Implements strict rate-limit control and caching to stay within API free-tier constraints.\n- Provides a complete end-to-end pipeline: universe building, data collection, scoring, report generation.\n- Uses kbs as primary data source, with vci fallback; excludes tcbs; disables Screener API by default.\n- Enforces required confidence rubric and clear reporting of coverage, risks, and missing data.\n- Includes generic method invocation scripts for broader vnstock package access.\n\nArchive index:\n\nArchive v1.0.3: 29 files, 78801 bytes\n\nFiles: _meta.json (138b), agents/openai.yaml (240b), references/capabilities.md (1125b), references/free_tier_playbook.md (891b), references/invocation_recipes.md (1285b), references/method_matrix.md (1190b), references/vnstock/01-overview.md (28095b), references/vnstock/02-installation.md (12228b), references/vnstock/03-listing-api.md (24904b), references/vnstock/04-company-api.md (21607b), references/vnstock/05-trading-api.md (9800b), references/vnstock/06-quote-price-api.md (13075b), references/vnstock/07-financial-api.md (25128b), references/vnstock/08-fund-api.md (5715b), references/vnstock/09-screener-api.md (215b), references/vnstock/10-connector-guide.md (11977b), references/vnstock/11-best-practices.md (14666b), references/vnstock/README.md (5901b), scripts/build_universe.py (3489b), scripts/catalog_vnstock.py (3439b), scripts/collect_fundamentals.py (3458b), scripts/collect_market_data.py (3471b), scripts/common.py (4475b), scripts/generate_report.py (2229b), scripts/invoke_vnstock.py (5084b), scripts/run_pipeline.py (2689b), scripts/score_stocks.py (2508b), skill-card.md (3348b), SKILL.md (7354b)\n\nFile v1.0.3:SKILL.md\n\n---\nname: vnstock-free-expert\ndescription: Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users request Vietnamese stock analysis under free-tier constraints.\ncompatibility: Requires Python 3.x, vnstock package, pandas, internet access, and optional VNSTOCK_API_KEY in .env.\n---\n\n# VNStock Free Expert\n\nUse this skill when the user needs advanced Vietnam stock analysis with `vnstock`, while staying safe on free-tier limits.\n\n## Important packaging note\nThis skill is self-contained and does not require shipping a separate `vnstock/` docs folder.\nAll operational knowledge needed by the agent is stored under:\n- `references/`\n\n## Read order\n1. Read `references/capabilities.md`.\n2. Read `references/method_matrix.md` for exact class/method mapping.\n3. Read `references/free_tier_playbook.md` before large runs.\n\n## Scope and constraints\n- Library: `vnstock` only.\n- Preferred sources: `kbs` first, `vci` fallback.\n- Never use `tcbs`.\n- Treat `Screener API` as unavailable unless user confirms it is restored in their installed version.\n\n## Free-tier operating rules\n- No API key: target <= 20 requests/minute.\n- Free API key: target <= 60 requests/minute.\n- Safe default pacing in scripts: 3.2s/request.\n- Reuse cached artifacts between steps.\n\n## Shared confidence rubric (required)\nReport confidence as `High` / `Medium` / `Low` using this standard:\n- `High`: universe coverage >= 95%, critical metrics coverage >= 80%, and hard errors <= 5% of symbols.\n- `Medium`: universe coverage >= 80%, critical metrics coverage >= 60%, and hard errors <= 15%.\n- `Low`: below `Medium` thresholds or material missing fields that can flip ranking results.\n\nAlways output:\n1. Confidence level.\n2. Coverage stats (`symbols_requested`, `symbols_scored`, `% missing by key metric`).\n3. Top missing fields that may change conclusions.\n\n## API key configuration (implemented)\n- Skill-local key file: `.env`\n- Variable: `VNSTOCK_API_KEY`\n- All API-calling scripts auto-load this key and call vnstock auth setup before requests.\n- You can override per run with `--api-key \"...\"`.\n\n## Execution workflow (ordered)\n1. Validate environment (`python`, `vnstock`, `pandas`) and load optional API key from `.env`.\n2. Build a universe using `scripts/build_universe.py` (`group`, `exchange`, or `symbols` mode).\n3. Collect market data with `scripts/collect_market_data.py` using safe pacing.\n4. Collect fundamentals with `scripts/collect_fundamentals.py`.\n5. Score and rank using `scripts/score_stocks.py`.\n6. Generate analyst-style memo with `scripts/generate_report.py`.\n7. Apply confidence rubric, disclose missing fields, and summarize risks.\n\n## Downstream handoff bundle (required when doing single-ticker deep dive)\nWhen the user request is about valuing or building a memo for a **specific ticker** (or a small list), output a compact JSON bundle that downstream skills can reuse:\n- `ticker`, `as_of_date`, `currency`\n- `financials` (income/balance/cashflow + key ratios if available)\n- `price_history` (returns 1m/3m/6m/12m)\n- `peer_set` (if you built one)\n- `metadata.source` and `data_quality_notes`\n\nHandoff stability rule:\n- Keep field names stable so downstream skills can consume the bundle without reinterpretation.\n- Never omit a required top-level key; use `null`, an empty object, or an empty list when data is unavailable.\n- Put provider errors and missing fields in `metadata.data_quality_notes`.\n\nThis bundle is designed to feed `equity-valuation-framework` and `portfolio-risk-manager`.\n\n## Script map\n\n### A) Discovery and universal invocation (for broad feature coverage)\n\n1. `catalog_vnstock.py`\nPath: `scripts/catalog_vnstock.py`\n\nUse when:\n- You need to inspect available classes/methods in the installed `vnstock` version.\n- You want to confirm compatibility before running a method.\n\n2. `invoke_vnstock.py`\nPath: `scripts/invoke_vnstock.py`\n\nUse when:\n- You need to call any supported class/method beyond the prebuilt valuation pipeline.\n- You want one generic entry point for `Listing`, `Quote`, `Company`, `Finance`, `Trading`, `Fund`, or other exported classes.\n\nThis script supports dynamic invocation by class name and method name with JSON kwargs.\n\n### B) Valuation pipeline scripts\n\n1. `build_universe.py`\nUse when building symbol universe from index/exchange/custom symbol list.\nInput: source + mode + group/exchange/symbols.\nOutput: `outputs/universe_*.csv` and latest pointers.\n\n2. `collect_market_data.py`\nUse when collecting OHLCV/momentum fields (3M, 6M, 12M returns).\nInput: universe CSV path.\nOutput: `outputs/market_data_*.csv` + per-symbol errors in JSON.\n\n3. `collect_fundamentals.py`\nUse when collecting valuation and quality metrics from finance/company APIs.\nInput: universe CSV path.\nOutput: `outputs/fundamentals_*.csv` + per-symbol errors in JSON.\n\n4. `score_stocks.py`\nUse when ranking symbols with composite scoring.\nInput: market + fundamentals CSV files.\nOutput: `outputs/ranking_*.csv`.\n\n5. `generate_report.py`\nUse when converting ranking output to analyst-style markdown memo.\nInput: ranking CSV file.\nOutput: `outputs/investment_memo_*.md`.\n\n6. `run_pipeline.py`\nUse when running the end-to-end pipeline in one command.\nInput: source + universe mode.\nOutput: all artifacts above in one run.\n\n## Error handling rules\n1. Log symbol-level failures and continue processing remaining symbols.\n2. Do not claim missing metrics as zeros; mark them as missing.\n3. If a critical step fails, stop and report failed step + command + suggested retry scope.\n\n## Recommended decision logic\n1. If request is “standard valuation/ranking”: run pipeline scripts.\n2. If request needs a specific vnstock capability not in pipeline: use `catalog_vnstock.py` then `invoke_vnstock.py`.\n3. If request volume is large: apply `free_tier_playbook.md` throttling and chunking strategy.\n\n## Confidence aggregation (required)\nWhen output includes ranking and valuation interpretation:\n1. Compute data confidence from coverage metrics (`symbols_scored`, missing key fields, error ratio).\n2. Compute model confidence from method robustness (single metric vs multi-factor consistency).\n3. Final confidence = lower of data confidence and model confidence.\n4. In `Low` confidence cases, provide directional output only and list required missing inputs.\n\n## Required output template\n1. `What Was Run`: scripts, source, universe scope, and pacing profile.\n2. `Coverage`: requested symbols, scored symbols, and missingness by key field.\n3. `Top Results`: ranked list with score columns.\n4. `Key Risks`: concentration, stale data, missing metrics, or provider limitations.\n5. `Confidence and Gaps`: final confidence + exact blockers.\n\n## Quick command examples\n```bash\npython scripts/catalog_vnstock.py --outdir ./outputs\npython scripts/invoke_vnstock.py --class-name Quote --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"VCB\"}' --method history --method-kwargs '{\"start\":\"2024-01-01\",\"end\":\"2024-12-31\",\"interval\":\"1D\"}' --outdir ./outputs\npython scripts/run_pipeline.py --source kbs --mode group --group VN30 --outdir ./outputs\n```\n\n## Trigger examples\n- \"Analyze VN30 using vnstock but keep it free-tier safe.\"\n- \"Rank Vietnamese stocks by value/quality/momentum with KBS data.\"\n- \"Run a full vnstock pipeline and return top candidates with risk notes.\"\n\nFile v1.0.3:references/vnstock/README.md\n\n# VNStock 3.4.0 - Tài Liệu Hướng Dẫn\n\n## 🎯 Giới Thiệu\n\n**VNStock** là thư viện Python để lấy dữ liệu chứng khoán Việt Nam từ nhiều nguồn uy tín. Thiết kế với kiến trúc provider-based, cho phép chuyển đổi linh hoạt giữa các nguồn dữ liệu khác nhau.\n\n### ✨ Tính Năng Chính\n\n- ✅ **Nhiều nguồn dữ liệu**: VCI, KBS, MSN (API công khai); FMP, DNSE (API chính thức)\n- ⚠️ **TCBS**: Ngưng cập nhật thêm từ v3.4.0, sẽ loại bỏ trong v3.5.0 (tháng 3/2026)\n- ✅ **API thống nhất**: Cùng interface cho tất cả nguồn\n- ✅ **Dữ liệu lịch sử & Real-time**: Giá, công ty, tài chính\n- ✅ **Dữ liệu công ty**: Hồ sơ, cổ đông, nhân viên quản lý\n- ✅ **Dữ liệu tài chính**: Báo cáo, chỉ số, lưu chuyển tiền tệ\n- ✅ **Lọc & Phân loại**: Theo ngành, sàn giao dịch, chỉ số\n\n## 📚 Hướng Dẫn Sử Dụng\n\n| Tài Liệu | Nội Dung | Mức Độ |\n|---------|---------|--------|\n| **[01-Overview](01-overview.md)** | Tổng quan kiến trúc, các loại dữ liệu | Cơ bản |\n| **[02-Installation](02-installation.md)** | Cài đặt, thiết lập, kiểm tra | Cơ bản |\n| **[03-Listing API](03-listing-api.md)** | API tìm kiếm và lọc chứng khoán | Cơ bản |\n| **[04-Company API](04-company-api.md)** | Thông tin công ty, cổ đông, nhân viên quản lý | Cơ bản |\n| **[05-Trading API](05-trading-api.md)** | Dữ liệu giao dịch, bid/ask, thống kê | Cơ bản |\n| **[06-Quote & Price](06-quote-price-api.md)** | API lấy giá lịch sử và real-time | Cơ bản |\n| **[07-Financial API](07-financial-api.md)** | API dữ liệu tài chính và báo cáo | Trung cấp |\n| **[08-Fund API](08-fund-api.md)** | Dữ liệu quỹ đầu tư mở (Fmarket) | Trung cấp |\n| **[09-Screener API](09-screener-api.md)** | Công cụ lọc chứng khoán nâng cao | Nâng cao |\n| **[10-Connector Guide](10-connector-guide.md)** | Hướng dẫn API bên ngoài (FMP, XNO, DNSE) | Nâng cao |\n| **[11-Best Practices](11-best-practices.md)** | Mẹo tối ưu hóa, xử lý lỗi, security | Nâng cao |\n\n## 🚀 Bắt Đầu Nhanh\n\n### Cài Đặt\n\n```bash\npip install vnstock\n```\n\nXem chi tiết tại **[02-Installation](02-installation.md)**\n\n## 📖 Cấu Trúc Tài Liệu\n\nTài liệu được chia thành 11 phần theo thứ tự từ cơ bản đến nâng cao:\n\n1. **[01-Overview](01-overview.md)** - Hiểu kiến trúc và các loại dữ liệu\n2. **[02-Installation](02-installation.md)** - Cài đặt và kiểm tra môi trường\n3. **[03-Listing API](03-listing-api.md)** - Tìm kiếm danh sách chứng khoán\n4. **[04-Company API](04-company-api.md)** - Lấy thông tin công ty chi tiết\n5. **[05-Trading API](05-trading-api.md)** - Dữ liệu giao dịch thị trường\n6. **[06-Quote & Price](06-quote-price-api.md)** - Lấy dữ liệu giá\n7. **[07-Financial API](07-financial-api.md)** - Truy cập dữ liệu tài chính\n8. **[08-Fund API](08-fund-api.md)** - Thông tin quỹ đầu tư mở\n9. **[09-Screener API](09-screener-api.md)** - Lọc chứng khoán nâng cao\n10. **[10-Connector Guide](10-connector-guide.md)** - Sử dụng API bên ngoài\n11. **[11-Best Practices](11-best-practices.md)** - Tối ưu hóa và xử lý lỗi\n\n## Kiến Trúc Hệ Thống\n\nVNStock sử dụng kiến trúc provider-based cho phép chuyển đổi linh hoạt giữa các nguồn dữ liệu:\n\n```\nỨng Dụng\n   ↓\nAPI Thống Nhất (Quote, Listing, Finance, Company)\n   ↓\nAdapter Layer (Chuẩn hóa dữ liệu)\n   ↓\nCác Nguồn Dữ Liệu (Web Scraping & API bên ngoài)\n```\n\n## 📊 Nguồn Dữ Liệu\n\n### Web Scraping\n\n| Nguồn | Danh Sách | Giá | Công Ty | Tài Chính | Trạng Thái |\n|-------|----------|-----|--------|----------|-----------|\n| **VCI** | ✅ | ✅ | ✅ | ✅ | Hoạt động |\n| **KBS** | ✅ | ✅ | ✅ | ✅ | Mới (v3.4.0) |\n| **MSN** | ✅ | ✅ | ❌ | ❌ | Hoạt động |\n\n### API Bên Ngoài\n\n| API | Giá | Tài Chính | Công Ty |\n|-----|-----|----------|---------|\n| **FMP** | ✅ | ✅ | ✅ |\n| **XNO** | ✅ | ✅ | ✅ |\n| **DNSE** | ✅ | ❌ | ❌ |\n\n## 🎓 Lộ Trình Học Tập\n\nKhuyến nghị làm theo thứ tự từ trên xuống để hiểu toàn bộ hệ thống:\n\n1. **[01-Overview](01-overview.md)** - Nắm vững kiến trúc và các khái niệm cơ bản\n2. **[02-Installation](02-installation.md)** - Cài đặt và xác nhận môi trường hoạt động\n3. **[03-Listing API](03-listing-api.md)** - Tìm kiếm chứng khoán theo tiêu chí\n4. **[03a-Company API](03a-company-api.md)** - Tìm hiểu chi tiết về công ty\n5. **[03b-Trading API](03b-trading-api.md)** - Phân tích dữ liệu giao dịch\n6. **[04-Quote & Price](04-quote-price-api.md)** - Truy cập dữ liệu giá chứng khoán\n7. **[05-Financial API](05-financial-api.md)** - Lấy dữ liệu tài chính chi tiết\n8. **[05a-Fund API](05a-fund-api.md)** - Khám phá quỹ đầu tư mở\n9. **[06-Connector Guide](06-connector-guide.md)** - Sử dụng API bên ngoài (FMP, XNO, DNSE)\n10. **[06a-Screener API](06a-screener-api.md)** - Lọc chứng khoán theo tiêu chí nâng cao\n11. **[07-Best Practices](07-best-practices.md)** - Áp dụng tối ưu hóa, xử lý lỗi, security\n\n## 🔗 Liên Kết Hữu Ích\n\n- **[GitHub](https://github.com/thinh-vu/vnstock)** - Mã nguồn và issue tracking\n- **[PyPI](https://pypi.org/project/vnstock)** - Cài đặt package\n- **[Website](https://vnstocks.com)** - Trang chính thức\n\n## ℹ️ Thông Tin Phiên Bản\n\n- **Phiên bản**: 3.4.0\n- **Cập nhật lần cuối**: 2024-12-17\n- **Trạng thái**: Đang bảo trì ✅\n- **Thông báo**: TCBS đã ngưng được cập nhật, sẽ loại bỏ trong v3.5.0 (tháng 3/2026)\n- **License**: MIT\n\nFile v1.0.3:_meta.json\n\n{\n  \"ownerId\": \"kn7aqz9b9xv2mmyvsg54n5kecn81kkaf\",\n  \"slug\": \"vnstock-free-expert\",\n  \"version\": \"1.0.3\",\n  \"publishedAt\": 1779409336119\n}\n\nFile v1.0.3:references/capabilities.md\n\n# VNStock Capability Reference (Self-Contained)\n\n## Core capabilities\n- Symbol universe and classification: exchanges, industries, index groups, derivatives/bonds/warrants listings.\n- Company intelligence: overview, shareholders, officers, subsidiaries, affiliates, events, reports (source-dependent).\n- Market data: historical OHLCV, intraday prints, board snapshots, market depth (source-dependent).\n- Financial statements and ratios: income statement, balance sheet, cash flow, ratio with period modes.\n- Fund data: investment fund listings and related metadata.\n- External connectors: available depending on environment and API keys.\n\n## Source strategy\n- Primary source: `kbs`.\n- Secondary fallback: `vci`.\n- Do not use `tcbs`.\n\n## Data caveats\n- Method availability differs by source.\n- Some methods may return empty frames for specific symbols/time windows.\n- Realtime/near-realtime outputs depend on market hours and provider freshness.\n\n## Safe analysis pattern\n1. Fetch raw data.\n2. Validate shape/columns.\n3. Handle empty/missing values.\n4. Compute derived metrics.\n5. Separate factual output from interpretation.\n\nFile v1.0.3:references/free_tier_playbook.md\n\n# Free-Tier Playbook\n\n## Rate limit profile\n- Guest/no key: 20 requests/minute.\n- Free key: up to 60 requests/minute.\n\n## Execution controls\n- Default minimum interval: 3.2 seconds/request.\n- For unstable network/provider: increase to 4-5 seconds/request.\n- Process symbols in chunks (e.g. 20-50 symbols/batch).\n\n## Resilience checklist\n- Retry transient failures with backoff.\n- Log per-symbol failures; do not fail the whole run if a single symbol fails.\n- Save intermediate artifacts (`universe`, `market_data`, `fundamentals`) for resume.\n\n## Data quality checklist\n- Confirm expected columns exist before calculation.\n- Track missing metrics ratio.\n- Flag stale data windows and low-bar histories.\n\n## Portfolio-analysis checklist\n- Use relative ranking, not absolute threshold only.\n- Validate top picks against recent macro/news context.\n- Apply sector diversification and risk caps.\n\nFile v1.0.3:references/invocation_recipes.md\n\n# Invocation Recipes\n\n## 1) Quote history\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Quote \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"VCB\"}' \\\n  --method history \\\n  --method-kwargs '{\"start\":\"2024-01-01\",\"end\":\"2024-12-31\",\"interval\":\"1D\"}' \\\n  --outdir ./outputs\n```\n\n## 2) Company overview\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Company \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"FPT\"}' \\\n  --method overview \\\n  --method-kwargs '{}' \\\n  --outdir ./outputs\n```\n\n## 3) Finance ratio (year)\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Finance \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"ACB\"}' \\\n  --method ratio \\\n  --method-kwargs '{\"period\":\"year\"}' \\\n  --outdir ./outputs\n```\n\n## 4) Listing by group\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Listing \\\n  --init-kwargs '{\"source\":\"kbs\"}' \\\n  --method symbols_by_group \\\n  --method-kwargs '{\"group\":\"VN30\"}' \\\n  --outdir ./outputs\n```\n\nFile v1.0.3:references/method_matrix.md\n\n# VNStock Method Matrix\n\nThis matrix lists common class-method combinations used in practice. Use `catalog_vnstock.py` to verify exact availability in the local installed version.\n\n## Listing\n- `all_symbols()`\n- `symbols_by_exchange()`\n- `symbols_by_industries()`\n- `industries_icb()`\n- `symbols_by_group()`\n- `all_indices()`\n- `indices_by_group()`\n- `all_future_indices()`\n- `all_government_bonds()`\n- `all_covered_warrant()`\n- `all_bonds()`\n\n## Quote\n- `history(...)`\n- `intraday(...)`\n- `price_depth(...)` (source-dependent)\n\n## Company\n- `overview()`\n- `shareholders()`\n- `officers()`\n- `subsidiaries()`\n- `affiliate()`\n- `news()`\n- `events()`\n- `ownership()` (source-dependent)\n- `capital_history()` (source-dependent)\n- `insider_trading()` (source-dependent)\n- `reports()` (source-dependent)\n- `trading_stats()` (source-dependent)\n- `ratio_summary()` (source-dependent)\n\n## Finance\n- `income_statement(period=...)`\n- `balance_sheet(period=...)`\n- `cash_flow(period=...)`\n- `ratio(period=...)`\n\n## Trading\n- `price_board(symbols_list=...)`\n\n## Fund\n- `listing(...)`\n\n## Universal method access\nUse `invoke_vnstock.py` for any class/method not explicitly hardcoded in pipeline scripts.\n\nFile v1.0.3:references/vnstock/01-overview.md\n\n# Vnstock 3.4.0 - Tổng Quan Kiến Trúc & Dữ Liệu\n\n**Phiên bản:** 3.4.0+  \n\n**Cập nhật:** Tháng 1, 2026  \n\n**Trạng thái:** Hoạt động\n\n---\n\n## 📚 Mục Lục\n\n1. [Giới Thiệu](#giới-thiệu)\n2. [Các Plan & Rate Limit](#các-plan--rate-limit)\n3. [Kiến Trúc Tổng Thể](#kiến-trúc-tổng-thể)\n4. [Phân Tầng Dữ Liệu (Data Layers)](#phân-tầng-dữ-liệu-data-layers)\n5. [Các APIs & Dữ Liệu Hiện Có](#các-apis--dữ-liệu-hiện-có)\n6. [Nguồn Dữ Liệu & Connectors](#nguồn-dữ-liệu--connectors)\n7. [Core Utilities](#core-utilities)\n8. [Cách Sử Dụng Cơ Bản](#cách-sử-dụng-cơ-bản)\n\n---\n\n## 📖 Giới Thiệu\n\n**Vnstock** là thư viện Python mạnh mẽ để lấy dữ liệu chứng khoán Việt Nam từ nhiều nguồn uy tín. Thư viện được thiết kế với kiến trúc provider-based, cho phép dễ dàng chuyển đổi giữa các nguồn dữ liệu khác nhau mà không thay đổi code.\n\n### 🎯 Đặc Điểm Chính\n\n- **Nhiều nguồn dữ liệu**: VCI, KBS, MSN, và các connectors bên ngoài (FMP, DNSE)\n- **API thống nhất**: Cùng một interface cho tất cả các nguồn dữ liệu\n- **Dữ liệu lịch sử & Real-time**: Giá lịch sử, dữ liệu trong ngày, giá realtime\n- **Dữ liệu công ty**: Hồ sơ công ty, cổ đông chính, nhân viên quản lý\n- **Dữ liệu tài chính**: Báo cáo tài chính, chỉ số tài chính, các dòng tiền\n- **Lọc & Phân loại**: Tìm kiếm theo ngành, sàn giao dịch, chỉ số\n- **Xử lý lỗi thông minh**: Retry tự động với exponential backoff\n\n⚠️ **TCBS**: Đã ngưng cập nhật từ v3.4.0, sẽ loại bỏ trong v3.5.0 (tháng 3/2026)\n\n---\n\n## 💳 So sánh các gói sử dụng & giới hạn\n\nVnstock cung cấp các gói sử dụng khác nhau phù hợp với từng nhu cầu cụ thể, xem thông tin chính xác được chia sẻ tại website Vnstock [Gói tài trợ Vnstock](https://vnstocks.com/insiders-program):\n\n### So sánh gói sử dụng\n\n| Tiêu Chí          | Khách | Cộng đồng (Tiêu chuẩn)  | Bronze    | Silver    | Golden    |\n| ----------------- | ----- | ----- | --------- | --------- | --------- |\n| **Giới Hạn/Phút** | 20    | 60    | 180 (3x)  | 300 (5x) | 500 (10x) |\n| **Giới Hạn/Giờ**  | 1.2K  | 3.6K  | 10.8K     | 18K       | 36K       |\n| **Giới Hạn/Ngày** | 5K    | 10K   | 50K       | 100K      | 150K      |\n| **Đăng Nhập**     | ❌    | ✅    | ✅        | ✅        | ✅        |\n| **API Key**       | ❌    | ✅    | ✅        | ✅        | ✅        |\n| **vnstock_data**  | ❌    | ❌    | ✅        | ✅        | ✅        |\n| **Hỗ Trợ**        | ❌    | ❌    | ✅        | ✅        | ✅        |\n| **Cam Kết**       | Không | Không | Linh Hoạt | Quý       | 1 Năm     |\n\n(*) **Lưu ý quan trọng về Rate Limit:**\n- Khi chạm giới hạn API, chương trình sẽ tự động dừng để bảo vệ hệ thống\n- Số lượng request trên mang tính tham khảo và có thể thay đổi\n- Giới hạn thực tế phụ thuộc vào: giới hạn của Vnstock và giới hạn của server nguồn dữ liệu\n- Khuyến nghị: Sử dụng cache dữ liệu để tối ưu hiệu suất\n\n### 🎯 Chọn Plan Nào?\n\n#### 1. **Guest** - Trải Nghiệm Nhanh\n\n- **Ai nên dùng**: Người mới, thử nghiệm, không cam kết\n- **Đặc điểm**: \n    - Không cần đăng nhập hay API key\n    - Giới hạn 20 request/phút (1.2K/giờ, 5K/ngày)\n    - Thích hợp cho khám phá nhanh\n- **Ví dụ**: `quote = Quote(source=\"vci\", symbol=\"VCB\")`\n\n#### 2. **Free** - Học Tập & Phát Triển\n\n- **Ai nên dùng**: Sinh viên, developer mới, người học Python\n- **Đặc điểm**:\n    - Cần đăng nhập tài khoản vnstock & API key\n    - Giới hạn 60 request/phút (3.6K/giờ, 10K/ngày) - **3x Guest**\n    - Đủ cho phát triển & kiểm thử cơ bản\n- **Cách bắt đầu**: Đăng ký miễn phí tại https://vnstocks.com/login\n- **Ví dụ**: \n\n  ```python\n  from vnstock import config\n  config.set_api_key(\"your_api_key\")\n  quote = Quote(source=\"vci\", symbol=\"VCB\")\n  ```\n\n#### 3. **Bronze** - Dữ Liệu Cơ Bản\n\n- **Ai nên dùng**: Nhà phân tích, trader cá nhân, startup\n- **Đặc điểm**:\n    - Giới hạn 180 request/phút (10.8K/giờ, 50K/ngày) - **9x Guest**\n    - Truy cập **vnstock_data** với dữ liệu nâng cao\n    - Plan linh hoạt (hàng tháng hoặc quý)\n    - Hỗ trợ cơ bản\n- **Tính năng nâng cao**: Xem [vnstock_data Overview](../vnstock-data/01-overview.md)\n- **Tham gia**: https://vnstocks.com/insiders-program\n\n#### 4. **Silver** - Chức Năng Mở Rộng\n\n- **Ai nên dùng**: nhóm, quản lý quỹ đầu tư, dự án công khai\n- **Đặc điểm**:\n    - Giới hạn 300 request/phút (18K/giờ, 100K/ngày) - **15x Guest**\n    - Truy cập hầu hết chức năng nâng cao của vnstock_data\n    - Plan quý (3 tháng)\n    - Hỗ trợ ưu tiên\n- **Tính năng nâng cao**: Xem [vnstock_data Overview](../vnstock-data/01-overview.md)\n- **Tham gia**: https://vnstocks.com/insiders-program\n\n#### 5. **Golden** - Toàn Bộ Chức Năng\n\n- **Ai nên dùng**: Dự án lâu dài, đồng hành bền vững cùng dự án\n- **Đặc điểm**:\n    - Giới hạn 600 request/phút (36K/giờ, 150K/ngày) - **30x Guest**\n    - Truy cập **tất cả** chức năng của bộ thư viện tài trợ\n    - Plan 1 năm (cam kết lâu dài)\n    - Hỗ trợ tối ưu & ưu đãi chi phí tốt nhất\n- **Tính năng nâng cao**: Xem [vnstock_data Overview](../vnstock-data/01-overview.md)\n- **Tham gia**: https://vnstocks.com/insiders-program\n\n### 📊 Rate Limit Chi Tiết\n\n```python\nTIER_LIMITS = {\n    \"guest\": {\"min\": 20, \"hour\": 1200, \"day\": 5000},\n    \"free\": {\"min\": 60, \"hour\": 3600, \"day\": 10000},\n    \"bronze\": {\"min\": 180, \"hour\": 10800, \"day\": 50000},\n    \"silver\": {\"min\": 300, \"hour\": 15000, \"day\": 100000},\n    \"golden\": {\"min\": 500, \"hour\": 30000, \"day\": 150000}\n}\n```\n\n### 🚀 Nâng Cấp\n\nKhi bạn gặp rate limit:\n\n```python\nfrom vnstock.core.quota import RateLimitExceeded\n\ntry:\n    quote = Quote(source=\"vci\", symbol=\"VCB\")\n    df = quote.history(start=\"2024-01-01\", end=\"2024-12-31\")\nexcept RateLimitExceeded as e:\n    print(e)  # Sẽ hiển thị hướng dẫn nâng cấp phù hợp\n```\n\n---\n\n## 🏗️ Kiến Trúc Tổng Thể\n\nVnstock được thiết kế theo **Adapter Pattern** với các tầng rõ ràng:\n\n```\n┌─────────────────────────────────────────┐\n│         User Code (Your App)            │\n├─────────────────────────────────────────┤\n│  Quote | Listing | Company | Finance    │  ← Unified API Layer\n│  Trading | Misc (Gold, FX)              │\n├─────────────────────────────────────────┤\n│  Provider Registry (Dynamic Discovery)  │\n├─────────────────────────────────────────┤\n│        Explorer (Web Scraping)          │\n│  ┌──────────────────────────────────┐   │\n│  │ VCI | KBS | MSN | FMarket        │   │\n│  └──────────────────────────────────┘   │\n│                                          │\n│    Connector (Official APIs)             │\n│  ┌──────────────────────────────────┐   │\n│  │ FMP | DNSE | Binance             │   │\n│  └──────────────────────────────────┘   │\n└─────────────────────────────────────────┘\n```\n\n### Cấu Trúc Thư Mục Hiện Tại\n\n```\nvnstock/\n├── api/                          # Unified API Layer (Facade)\n│   ├── __init__.py\n│   ├── quote.py                  # Quote API\n│   ├── company.py                # Company API\n│   ├── financial.py              # Finance API\n│   ├── trading.py                # Trading API\n│   ├── listing.py                # Listing API\n│   └── ...\n│\n├── explorer/                     # Data Explorers (Source-specific)\n│   ├── kbs/                      # KB Securities\n│   │   ├── quote.py\n│   │   ├── company.py\n│   │   ├── financial.py\n│   │   ├── trading.py\n│   │   ├── listing.py\n│   │   └── const.py\n│   │\n│   ├── vci/                      # VCI\n│   │   ├── quote.py\n│   │   ├── company.py\n│   │   ├── financial.py\n│   │   ├── trading.py\n│   │   ├── listing.py\n│   │   └── const.py\n│   │\n│   ├── misc/                     # Miscellaneous (Utilities)\n│   │   ├── gold_price.py         # Giá vàng\n│   │   └── exchange_rate.py      # Tỷ giá ngoại tệ\n│   │\n│   └── ... (MAS, VND, CafeF, FMarket, MBK, SPL, MSN, TCBS, v.v.)\n│\n├── connector/                    # Low-level Connectors\n│   ├── dnse/                     # DNSE Trading\n│   ├── fmp/                      # FMP (Financial Modeling Prep)\n│   ├── binance/                  # Binance (Crypto - sắp tới)\n│   └── ...\n│\n├── core/                         # Core Utilities & Infrastructure\n│   ├── utils/\n│   │   ├── market.py             # Giờ giao dịch, trạng thái thị trường\n│   │   ├── interval.py           # Xử lý timeframe (1D, 1H, 1m, v.v.)\n│   │   ├── lookback.py           # Xử lý lookback period (1M, 3M, 100D, v.v.)\n│   │   ├── transform.py          # Chuyển đổi dữ liệu (long/wide format)\n│   │   ├── parser.py             # Parse dữ liệu từ các nguồn\n│   │   ├── validation.py         # Kiểm tra dữ liệu\n│   │   ├── auth.py               # Xác thực API key\n│   │   ├── client.py             # HTTP client\n│   │   ├── proxy_manager.py      # Quản lý proxy\n│   │   ├── logger.py             # Logging\n│   │   └── ... (19+ utilities)\n│   │\n│   ├── types.py                  # Type definitions\n│   ├── models.py                 # Data models\n│   ├── registry.py               # Provider registry\n│   └── ...\n│\n├── base.py                       # Base classes (BaseAdapter, etc.)\n├── config.py                     # Configuration\n├── constants.py                  # Constants\n└── __init__.py                   # Package initialization\n```\n\n### Cách Hoạt Động\n\n1. **Adapter Layer**: Bạn sử dụng các class như `Quote`, `Listing`, `Company` v.v.\n2. **Provider Registry**: Thư viện tìm kiếm provider phù hợp dựa trên `source` parameter\n3. **Dynamic Method Detection**: Chỉ các phương thức mà provider hỗ trợ mới được gọi\n4. **Parameter Filtering**: Tự động lọc tham số để phù hợp với provider signature\n\n---\n\n## 📊 Phân Tầng Dữ Liệu (Data Layers)\n\nVnstock tổ chức dữ liệu thành các tầng theo mô hình tham khảo từ các nguồn quốc tế như Bloomberg Terminal, FinancialModelingPrep, vv\n\n### Tầng 1: Reference Data (Dữ Liệu Tham Chiếu)\n\n**Mục đích:** Master data, identifiers, classifications\n\n**Dữ Liệu Hiện Có:**\n\n- **Listing API**: Danh sách chứng khoán, chỉ số, sàn giao dịch\n- **Company API**: Thông tin công ty, cổ đông, ban lãnh đạo\n\n**Methods:**\n\n```python\nfrom vnstock import Listing, Company\n\n# Listing - Danh sách chứng khoán\nlisting = Listing(source=\"vci\")\nsymbols = listing.all_symbols()           # Tất cả mã chứng khoán\nindices = listing.indices()               # Danh sách chỉ số\nbonds = listing.government_bonds()        # Trái phiếu (VCI only)\n\n# Company - Thông tin công ty\ncompany = Company(source=\"vci\", symbol=\"VCB\")\nprofile = company.overview()              # Thông tin tổng quan\nshareholders = company.shareholders()     # Cổ đông lớn\nofficers = company.officers()             # Ban lãnh đạo\nsubsidiaries = company.subsidiaries()     # Công ty con\ncapital_history = company.capital_history()  # Lịch sử vốn (KBS only)\n```\n\n---\n\n### Tầng 2: Market Data (Dữ Liệu Thị Trường)\n\n**Mục đích:** Giá, khối lượng, sổ lệnh, dữ liệu tick\n\n**Dữ Liệu Hiện Có:**\n\n- **Quote API**: Giá lịch sử, intraday, sổ lệnh\n- **Trading API**: Bảng giá, thống kê giao dịch\n\n**Methods:**\n\n```python\nfrom vnstock import Quote, Trading\n\n# Quote - Dữ liệu giá\nquote = Quote(source=\"vci\", symbol=\"VCB\")\nhistory = quote.history(\n    start=\"2024-01-01\",\n    end=\"2024-12-31\",\n    interval=\"1D\"  # 1D, 1H, 1m, 5m, 15m, 30m\n)\nintraday = quote.intraday()               # Dữ liệu trong ngày\ndepth = quote.price_depth()               # Sổ lệnh\n\n# Trading - Dữ liệu giao dịch\ntrading = Trading(source=\"vci\")\nboard = trading.price_board([\"VCB\", \"VNM\"])  # Bảng giá\nprice_history = trading.price_history()      # Lịch sử giá (VCI only)\ntrading_stats = trading.trading_stats()      # Thống kê giao dịch (VCI only)\n```\n\n**Hỗ trợ TimeFrame:**\n\n- Intraday: `1m`, `5m`, `15m`, `30m`, `1H`, `4h`\n- Daily+: `1D`, `1W`, `1M`\n\n---\n\n### Tầng 3: Fundamental Data (Dữ Liệu Cơ Bản)\n\n**Mục đích:** Báo cáo tài chính, chỉ số, tỷ lệ\n\n**Dữ Liệu Hiện Có:**\n\n- **Finance API**: Báo cáo tài chính (Income, Balance Sheet, Cash Flow, Ratios)\n\n**Methods:**\n\n```python\nfrom vnstock import Finance\n\nfinance = Finance(source=\"vci\", symbol=\"VCB\")\n\n# Báo cáo tài chính\nincome = finance.income_statement(period=\"year\")      # Báo cáo thu nhập\nbalance = finance.balance_sheet(period=\"quarter\")     # Bảng cân đối\ncashflow = finance.cash_flow(period=\"year\")           # Dòng tiền\nratios = finance.ratio(period=\"year\")                 # Chỉ số tài chính\n```\n\n**Hỗ trợ Periods:**\n\n- `year` - Hàng năm\n- `quarter` - Hàng quý\n\n---\n\n### Tầng 4: Alternative Data (Dữ Liệu Thay Thế)\n\n**Mục đích:** Tin tức, sự kiện, dữ liệu tiện ích\n\n**Dữ Liệu Hiện Có:**\n\n- **Company.news()**: Tin tức công ty\n- **Misc utilities**: Giá vàng, tỷ giá ngoại tệ\n\n**Methods:**\n\n```python\nfrom vnstock import Company\nfrom vnstock.explorer.misc import GoldPrice, ExchangeRate\n\n# Tin tức\ncompany = Company(source=\"vci\", symbol=\"VCB\")\nnews = company.news()\n\n# Giá vàng\ngold = GoldPrice()\ngold_price = gold.get_latest()\n\n# Tỷ giá ngoại tệ\nfx = ExchangeRate()\nusd_vnd = fx.get_rate(\"USD\", \"VND\")\n```\n\n---\n\n### Tầng 5-7: Analytics, Macro, Insights\n\n**Trạng thái:** Chưa triển khai đầy đủ\n\n- **Layer 5 (Analytics)**: Chỉ số kỹ thuật, mô hình định giá, vv (chưa đầy đủ) - có thư viện vnstock_ta cung cấp tính toán bộ chỉ báo kỹ thuật.​\n- **Layer 6 (Macro)**: Chỉ số kinh tế, hàng hóa - chỉ có trong thư viện vnstock_data yêu cầu tham gia gói tài trợ Vnstock.\n- **Layer 7 (Insights)**: Screener, rankings top stocks, vv - (Chưa đầy đủ) - chỉ có trong thư viện vnstock_data yêu cầu tham gia gói tài trợ Vnstock.\n\n---\n\n## 📋 Các APIs & Dữ Liệu Hiện Có\n\n### 1. Quote API - Dữ Liệu Giá\n\n| Method          | Mô Tả                        | Sources            |\n| --------------- | ---------------------------- | ------------------ |\n| `history()`     | Dữ liệu lịch sử OHLCV        | KBS, VCI, MSN, FMP |\n| `intraday()`    | Dữ liệu giao dịch trong ngày | KBS, VCI           |\n| `price_depth()` | Sổ lệnh (order book)         | KBS, VCI           |\n\n**Ứng Dụng:** Phân tích kỹ thuật, backtest chiến lược, tính toán chỉ số\n\n---\n\n### 2. Company API - Thông Tin Công Ty\n\n| Method              | Mô Tả               | Sources             |\n| ------------------- | ------------------- | ------------------- |\n| `overview()`        | Thông tin tổng quan | KBS, VCI, TCBS, FMP |\n| `officers()`        | Ban lãnh đạo        | KBS, VCI, TCBS      |\n| `shareholders()`    | Cổ đông lớn         | KBS, VCI, TCBS      |\n| `subsidiaries()`    | Công ty con         | KBS, VCI, TCBS      |\n| `news()`            | Tin tức             | KBS, VCI, TCBS      |\n| `capital_history()` | Lịch sử vốn         | KBS only            |\n| `ratio_summary()`   | Tóm tắt chỉ số      | VCI only            |\n\n**Ứng Dụng:** Nghiên cứu công ty, phân tích quản trị, theo dõi thay đổi cấp quản lý\n\n---\n\n### 3. Finance API - Báo Cáo Tài Chính\n\n| Method               | Mô Tả                | Sources             |\n| -------------------- | -------------------- | ------------------- |\n| `income_statement()` | Báo cáo thu nhập     | KBS, VCI, TCBS, FMP |\n| `balance_sheet()`    | Bảng cân đối kế toán | KBS, VCI, TCBS, FMP |\n| `cash_flow()`        | Báo cáo dòng tiền    | KBS, VCI, TCBS, FMP |\n| `ratio()`            | Chỉ số tài chính     | KBS, VCI, TCBS, FMP |\n\n**Ứng Dụng:** Phân tích cơ bản, định giá công ty, so sánh ngành\n\n---\n\n### 4. Trading API - Dữ Liệu Giao Dịch\n\n| Method            | Mô Tả              | Sources        |\n| ----------------- | ------------------ | -------------- |\n| `price_board()`   | Bảng giá realtime  | KBS, VCI, TCBS |\n| `price_history()` | Lịch sử giá        | VCI only       |\n| `trading_stats()` | Thống kê giao dịch | VCI only       |\n| `side_stats()`    | Thống kê mua/bán   | VCI only       |\n\n**Ứng Dụng:** Theo dõi giá thị trường, phân tích dòng tiền\n\n---\n\n### 5. Listing API - Danh Sách Chứng Khoán\n\n| Method                  | Mô Tả                 | Sources            |\n| ----------------------- | --------------------- | ------------------ |\n| `all_symbols()`         | Tất cả mã chứng khoán | KBS, VCI, MSN, FMP |\n| `symbols_by_exchange()` | Mã theo sàn           | VCI only           |\n| `government_bonds()`    | Trái phiếu chính phủ  | VCI only           |\n| `indices()`             | Danh sách chỉ số      | VCI, MSN, FMP      |\n\n**Ứng Dụng:** Xây dựng danh sách chứng khoán, lọc theo tiêu chí\n\n---\n\n### 6. Misc/Utils - Dữ Liệu Tiện Ích\n\n| Module         | Mô Tả           | Source       |\n| -------------- | --------------- | ------------ |\n| `GoldPrice`    | Giá vàng        | Web scraping |\n| `ExchangeRate` | Tỷ giá ngoại tệ | Web scraping |\n\n**Ứng Dụng:** Theo dõi giá vàng, chuyển đổi tiền tệ\n\n---\n\n## 🔌 Nguồn Dữ Liệu & Connectors\n\n### Explorer (Web Scraping)\n\n| Nguồn       | Domain       | Hỗ Trợ                                    | Phương Pháp  | Trạng Thái      |\n| ----------- | ------------ | ----------------------------------------- | ------------ | --------------- |\n| **VCI**     | vci.com.vn   | Quote, Listing, Company, Finance, Trading | Web Scraping | ✅ Hoạt động    |\n| **KBS**     | kbsec.com.vn | Quote, Listing, Company, Finance, Trading | Web Scraping | ✅ Mới (v3.4.0) |\n| **MSN**     | msn.com      | Quote, Listing                            | Web Scraping | ✅ Hoạt động    |\n| **FMarket** | fmarket.vn   | Listing (Fund)                            | Web Scraping | ✅ Hoạt động    |\n| **TCBS**    | tcbs.com.vn  | Quote, Listing, Company, Finance, Trading | Web Scraping | ⚠️ Ngưng hỗ trợ  |\n\n### Connector (Official APIs)\n\n| API         | Domain                    | Đặc Điểm                   | Chi Phí  | Trạng Thái   |\n| ----------- | ------------------------- | -------------------------- | -------- | ------------ |\n| **FMP**     | financialmodelingprep.com | Dữ liệu tài chính toàn cầu | Freemium | ✅ Hoạt động |\n| **DNSE**    | dnse.vn                   | API giao dịch  | Miễn phí   | ✅ Hoạt động |\n| **Binance** | binance.com               | Dữ liệu crypto             | Miễn phí | 📋 Sắp tới  |\n\n---\n\n## 🛠️ Core Utilities\n\nVnstock cung cấp các utilities hỗ trợ:\n\n### Market Utilities (`core/utils/market.py`)\n\n- `trading_hours()` - Lấy giờ giao dịch\n- `is_trading_hour()` - Kiểm tra giờ giao dịch\n- `market_status()` - Trạng thái thị trường (preparing, real_time, settling, historical_only)\n\n### Interval Utilities (`core/utils/interval.py`)\n\n- Chuẩn hóa timeframe: `1D`, `1H`, `1m`, `5m`, `15m`, `30m`, `1W`, `1M`\n- Hỗ trợ aliases: `d`, `h`, `m`, `w`, `M`\n\n### Lookback Utilities (`core/utils/lookback.py`)\n\n- Xử lý lookback periods: `1M`, `3M`, `6M`, `1Y`, `3Y`, `5Y`, `100D`, v.v.\n\n### Transform Utilities (`core/utils/transform.py`)\n\n- Chuyển đổi format: Long ↔ Wide, DataFrame ↔ JSON\n\n### Validation & Auth\n\n- `validation.py` - Kiểm tra dữ liệu\n\n---\n\n## 📈 Các Loại Dữ Liệu Chi Tiết\n\n### 1. Dữ Liệu Giá (Quote Data)\n\n```\n- Giá lịch sử: Open, High, Low, Close, Volume\n- Dữ liệu trong ngày (Intraday)\n- Bảng giá realtime\n- Độ sâu giá (Price Depth / Order Book)\n```\n\n### 2. Dữ Liệu Danh Sách (Listing Data)\n\n```\n- Tất cả mã chứng khoán\n- Lọc theo sàn giao dịch (HOSE, HNX, UPCOM)\n- Lọc theo ngành (ICB Industries)\n- Lọc theo chỉ số (VN30, VNMID, VNSML, v.v.)\n- Futures, Bonds, Warrants, Funds\n```\n\n### 3. Dữ Liệu Công Ty (Company Data)\n\n```\n- Hồ sơ công ty\n- Thông tin cổ đông chính\n- Danh sách nhân viên quản lý\n- Công ty con & chi nhánh\n- Tin tức & sự kiện\n```\n\n### 4. Dữ Liệu Tài Chính (Financial Data)\n\n```\n- Báo cáo tài chính:\n  ├─ Bảng cân đối kế toán (Balance Sheet)\n  ├─ Báo cáo kết quản kinh doanh (Income Statement)\n  ├─ Lưu chuyển tiền tệ (Cash Flow)\n  └─ Chỉ số tài chính (Ratios)\n- Theo kỳ: Hàng quý (Quarter) hoặc hàng năm (Year)\n```\n\n### 5. Dữ Liệu Giao Dịch (Trading Data)\n\n```\n- Khối lượng giao dịch\n- Giá trị giao dịch\n- Giao dịch cổ đông lớn\n- Lịch sử chia cổ tức\n```\n\n---\n\n## 💱 Sàn Giao Dịch (Exchanges)\n\n```\n- HOSE: Sở giao dịch Hà Nội (HOSE) - Thị trường chính\n- HNX: Sở giao dịch Hà Nội (HNX) - Thị trường phụ\n- UPCOM: Thị trường chứng khoán chưa niêm yết (UPCOM)\n```\n\n---\n\n## 📑 Chỉ Số Thị Trường (Indices)\n\n### Chỉ Số HOSE (6 chỉ số)\n\n- **VN30**: 30 cổ phiếu vốn hóa lớn nhất & thanh khoản tốt nhất\n- **VN100**: 100 cổ phiếu có vốn hoá lớn nhất HOSE\n- **VNMID**: Mid-Cap Index - nhóm cổ phiếu vốn hóa trung bình\n- **VNSML**: Small-Cap Index - nhóm cổ phiếu vốn hóa nhỏ\n- **VNALL**: Tất cả cổ phiếu trên HOSE và HNX\n- **VNSI**: Vietnam Small-Cap Index\n\n### Chỉ Số Ngành (10 chỉ số ICB)\n\n- **VNIT**: Công nghệ thông tin\n- **VNIND**: Công nghiệp\n- **VNCONS**: Hàng tiêu dùng\n- **VNCOND**: Hàng tiêu dùng thiết yếu\n- **VNHEAL**: Chăm sóc sức khoẻ\n- **VNENE**: Năng lượng\n- **VNUTI**: Dịch vụ tiện ích\n- **VNREAL**: Bất động sản\n- **VNFIN**: Tài chính\n- **VNMAT**: Nguyên vật liệu\n\n### Chỉ Số Đầu Tư (3 chỉ số)\n\n- **VNDIAMOND**: Chỉ số các cổ phiếu có triển vọng lớn\n- **VNFINLEAD**: Chỉ số tài chính đầu ngành\n- **VNFINSELECT**: Chỉ số tài chính được chọn lọc\n\n---\n\n## 🔄 Cách Sử Dụng Cơ Bản\n\n### Khởi Tạo\n\n```python\nfrom vnstock import Quote, Listing, Company, Finance, Trading\n\n# Quote - Giá chứng khoán\nquote = Quote(source=\"vci\", symbol=\"VCB\")\n\n# Listing - Danh sách chứng khoán\nlisting = Listing(source=\"vci\")\n\n# Company - Dữ liệu công ty\ncompany = Company(source=\"vci\", symbol=\"VCB\")\n\n# Finance - Dữ liệu tài chính\nfinance = Finance(source=\"vci\", symbol=\"VCB\")\n\n# Trading - Dữ liệu giao dịch\ntrading = Trading(source=\"vci\")\n```\n\n### Parameters Phổ Biến\n\n```python\n# Common parameters\nQuote(\n    source=\"vci\",           # Nguồn dữ liệu: vci, kbs, msn, fmp, etc.\n    symbol=\"VCB\",           # Mã chứng khoán\n    random_agent=False,     # Sử dụng random user agent\n    show_log=False          # Hiển thị log chi tiết\n)\n```\n\n### Chỉ Định Source\n\n```python\nfrom vnstock.core.types import DataSource\n\n# Liệt kê tất cả available sources\nprint(DataSource.all_sources())\n# Output: ['vci', 'kbs', 'msn', 'dnse', 'fmp', 'fmarket']\n\n# Sử dụng enum\nquote_vci = Quote(source=DataSource.VCI, symbol=\"VCB\")\nquote_kbs = Quote(source=DataSource.KBS, symbol=\"VCB\")\nquote_msn = Quote(source=DataSource.MSN, symbol=\"VCB\")\n\n# ⚠️ TCBS đã ngưng được hỗ trợ, không nên sử dụng\n```\n\n---\n\n## 🛡️ Xử Lý Lỗi & Retry\n\nVnstock tự động xử lý lỗi tạm thời với:\n\n- **Retry tự động**: Tối đa 5 lần (có thể cấu hình)\n- **Exponential Backoff**: Tăng độ trễ giữa các lần thử\n- **Timeout thông minh**: Tránh treo khi kết nối chậm\n\n```python\nfrom vnstock.config import Config\n\n# Tuỳ chỉnh retry behavior\nConfig.RETRIES = 3  # Số lần retry\nConfig.BACKOFF_MULTIPLIER = 2  # Hệ số backoff\nConfig.BACKOFF_MIN = 1  # Độ trễ tối thiểu (giây)\nConfig.BACKOFF_MAX = 30  # Độ trễ tối đa (giây)\n```\n\n---\n\n## 📚 Cấu Trúc Dữ Liệu Trả Về\n\n### DataFrame (Pandas)\n\nHầu hết các phương thức trả về `pd.DataFrame`:\n\n```python\ndf = quote.history(\n    symbol=\"VCB\",\n    start=\"2024-01-01\",\n    end=\"2024-12-31\"\n)\n\n# Output: DataFrame với các cột\n# Columns: time, open, high, low, close, volume, value\n```\n\n### Dictionary\n\nMột số phương thức trả về `dict`:\n\n```python\nprofile = company.overview()\n\n# Output: Dictionary với thông tin công ty\n# {\n#     'symbol': 'VCB',\n#     'company_name': '...',\n#     'exchange': 'HOSE',\n#     ...\n# }\n```\n\n### List\n\nDanh sách:\n\n```python\nsymbols = listing.all_symbols()\n\n# Output: List of strings\n# ['AAA', 'AAH', 'AAT', 'ABS', 'ABT', ...]\n```\n\n---\n\n## ✅ Kiểm Tra Lỗi Thường Gặp\n\n### 1. ValueError: Invalid Source\n\n```python\n# ❌ Sai\nquote = Quote(source=\"invalid_source\", symbol=\"VCB\")\n\n# ✅ Đúng\nquote = Quote(source=\"vci\", symbol=\"VCB\")\n```\n\n### 2. NotImplementedError\n\n```python\n# ❌ Sai - MSN không hỗ trợ Finance\nfinance = Finance(source=\"msn\", symbol=\"VCB\")\ndf = finance.balance_sheet()  # NotImplementedError\n\n# ✅ Đúng - Sử dụng KBS hoặc VCI\nfinance = Finance(source=\"kbs\", symbol=\"VCB\")\ndf = finance.balance_sheet()\n```\n\n### 3. TCBS Deprecated\n\n```python\n# ❌ Không nên sử dụng\nquote = Quote(source=\"tcbs\", symbol=\"VCB\")\n\n# ✅ Sử dụng KBS hoặc VCI thay thế\nquote = Quote(source=\"vci\", symbol=\"VCB\")\n```\n\n---\n\n## 🔗 Bước Tiếp Theo\n\n1. **[02-Installation](02-installation.md)** - Cài đặt & cấu hình\n2. **[03-Listing API](03-listing-api.md)** - Tìm kiếm chứng khoán\n3. **[04-Quote & Price](04-quote-price-api.md)** - Giá lịch sử & realtime\n4. **[05-Financial API](05-financial-api.md)** - Dữ liệu tài chính\n5. **[06-Company API](06-company-api.md)** - Thông tin công ty\n6. **[07-Trading API](07-trading-api.md)** - Dữ liệu giao dịch\n7. **[08-Best Practices](08-best-practices.md)** - Mẹo & kinh nghiệm\n\n---\n\n**Last Updated**: Tháng 1, 2026  \n\n**Version**: 3.4.0  \n\n**Status**: Hoạt động  \n\n**Important**: TCBS đã ngưng được hỗ trợ, sẽ bị loại bỏ vào khoảng tháng 3/2026.\n\nFile v1.0.3:references/vnstock/02-installation.md\n\n# 02 - Cài Đặt & Cấu Hình\n\n## 📦 Yêu Cầu Hệ Thống\n\n- **Python**: 3.8 hoặc cao hơn (khuyến nghị 3.10+)\n- **OS**: Windows, macOS, hoặc Linux\n- **Internet**: Kết nối internet ổn định\n\n## 🚀 Cài Đặt Nhanh\n\n### Option 1: Cài từ PyPI (Stable)\n\n```bash\npip install vnstock\n```\n\n### Option 2: Cài từ GitHub (Latest Development)\n\n```bash\npip install git+https://github.com/vnstock-lab/vnstock.git\n```\n\n### Option 3: Cài từ Local (Dev Version)\n\n```bash\n# Clone hoặc copy thư mục private_packages\npip install git+https://github.com/vnstock-lab/vnstock.git\n```\n\n## 📋 Dependencies\n\nVNStock phụ thuộc vào các package sau:\n\n```\npandas>=1.3.0          # Xử lý DataFrame\nrequests>=2.25.0       # HTTP requests\nbeautifulsoup4>=4.9.0  # Web scraping\nlxml>=4.6.0            # XML parsing\npydantic>=1.8.0        # Data validation\ntenacity>=8.0.0        # Retry logic\npython-dateutil>=2.8.0 # Date utilities\naiohttp>=3.7.0         # Async HTTP\ntqdm>=4.60.0           # Progress bars\npackaging>=20.0        # Version parsing\npython-dotenv>=0.19.0  # Env file support\n```\n\n### Cài đặt tự động (Recommended)\n\n```bash\n# Tất cả dependencies sẽ tự động được cài\npip install vnstock\n```\n\n### Cài đặt thủ công\n\n```bash\npip install pandas requests beautifulsoup4 lxml pydantic tenacity \\\n    python-dateutil aiohttp tqdm packaging python-dotenv\n```\n\n## Xác Thực API Key\n\nVNStock hỗ trợ các cấp độ sử dụng khác nhau với giới hạn requests tương ứng:\n\n### Cấp Độ Sử Dụng\n\n| Cấp độ | Giới hạn | Yêu cầu | Mô tả |\n|--------|----------|---------|-------|\n| **Khách (Guest)** | 20 requests/phút | Không cần đăng ký | Sử dụng miễn phí, giới hạn thấp |\n| **Cộng đồng (Community)** | 60 requests/phút | Đăng ký miễn phí | Phù hợp cá nhân mới tìm hiểu |\n| **Tài trợ (Sponsor)** | 180-600 requests/phút | Thành viên tài trợ| Dành cho nghiên cứu chuyên sâu |\n\n### Đăng Ký API Key (Miễn Phí)\n\n** 1. Đăng ký tương tác**\n\n```python\nfrom vnstock.core.utils.auth import register_user\n\n# Chạy đăng ký tương tác\nregister_user()\n```\n\nQuá trình đăng ký sẽ:\n1. Kiểm tra nếu đã có API key\n2. Hướng dẫn đến trang đăng nhập: https://vnstocks.com/login\n3. Nhập API key từ tài khoản Vnstock của người dùng\n4. Lưu và xác thực API key\n\n** 2. Đổi API key**\n\n1. Truy cập https://vnstocks.com/login\n2. Đăng nhập bằng tài khoản Google\n3. Lấy API key từ trang quản lý tài khoản\n4. Lưu API key bằng code:\n\n```python\nfrom vnstock.core.utils.auth import change_api_key\n\n# Thay đổi API key\nchange_api_key(\"your_api_key_here\")\n```\n\n### Kiểm Tra Trạng Thái\n\n```python\nfrom vnstock.core.utils.auth import check_status\n\n# Kiểm tra trạng thái hiện tại\nstatus = check_status()\n# Output:\n# ✓ API key: ab12***ef34\n#   Tier: Community\n#   Giới hạn: 60 requests/phút\n```\n\n### Sử Dụng Sau Khi Đăng Ký\n\nSau khi đăng ký API key, VNStock sẽ tự động sử dụng key cho tất cả requests:\n\n```python\nfrom vnstock import Quote, Listing\n\n# Sẽ tự động sử dụng API key đã đăng ký\nquote = Quote(source=\"KBS\", symbol=\"VCI\")\ndf = quote.history(start=\"2024-01-01\", end=\"2024-12-31\")\n\n# Không cần cấu hình thêm gì!\n```\n\n### Lưu Ý Quan Trọng\n\n- **API key được lưu trữ**: Không cần nhập lại. Nếu chạy trên môi trường Google Colab, sẽ phải lặp lại nhập API key mỗi lần sử dụng.\n- **Miễn phí**: Sử dụng bậc miễn phí dành cho đào tạo cộng đồng với nhu cầu trải nghiệm thấp\n- **Google OAuth**: Đăng nhập nhanh bằng tài khoản Google\n\n## � Cấu Hình\n\n### 1. Basic Configuration\n\nVNStock có thể dùng ngay sau khi cài đặt mà không cần cấu hình:\n\n```python\nfrom vnstock import Quote, Listing\n\n# Khởi tạo với KBS (khuyến nghị)\nquote = Quote(source=\"KBS\", symbol=\"VCI\")\nlisting = Listing(source=\"KBS\")\n\n# Hoặc VCI\nquote_kbs = Quote(source=\"VCI\", symbol=\"VCI\")\nlisting_kbs = Listing(source=\"VCI\")\n```\n\n### 2. Environment Variables\n\nTạo file `.env` trong project directory:\n\n```bash\n# .env file\nVNSTOCK_TIMEOUT=30\nVNSTOCK_RETRIES=5\nVNSTOCK_BACKOFF_MULTIPLIER=2\n```\n\nLoad trong code:\n\n```python\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\ntimeout = os.getenv('VNSTOCK_TIMEOUT', '30')\nretries = os.getenv('VNSTOCK_RETRIES', '5')\n```\n\n### 3. Configuration Object\n\n```python\nfrom vnstock.config import Config\n\n# Thay đổi cấu hình\nConfig.RETRIES = 3\nConfig.BACKOFF_MULTIPLIER = 2\nConfig.BACKOFF_MIN = 1\nConfig.BACKOFF_MAX = 30\nConfig.TIMEOUT = 30\n```\n\n### 4. External API Keys\n\nNếu sử dụng external APIs như FMP, XNO, DNSE:\n\n```bash\n# .env file\nFMP_API_KEY=your_fmp_api_key_here\nXNO_API_KEY=your_xno_api_key_here\nDNSE_API_KEY=your_dnse_api_key_here\nBINANCE_API_KEY=your_binance_key_here\nBINANCE_API_SECRET=your_binance_secret_here\n```\n\nLoad trong code:\n\n```python\nfrom vnstock import Quote\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n# Sử dụng FMP API\nquote = Quote(\n    source=\"fmp\",\n    symbol=\"VCI\",\n    api_key=os.getenv('FMP_API_KEY')\n)\n```\n\n## ✅ Kiểm Tra Cài Đặt\n\n### 1. Kiểm Tra Import\n\n```python\n# test_installation.py\nimport sys\n\nprint(\"📦 Checking imports...\")\n\ntry:\n    from vnstock import Quote, Listing, Company, Finance, Trading, Screener\n    print(\"✅ All main classes imported successfully\")\nexcept ImportError as e:\n    print(f\"❌ Import Error: {e}\")\n    sys.exit(1)\n\ntry:\n    from vnstock.core.types import DataSource, TimeFrame\n    print(\"✅ Core types imported successfully\")\nexcept ImportError as e:\n    print(f\"❌ Core types Error: {e}\")\n    sys.exit(1)\n\ntry:\n    from vnstock.constants import INDICES_INFO, EXCHANGES, SECTOR_IDS\n    print(\"✅ Constants imported successfully\")\nexcept ImportError as e:\n    print(f\"❌ Constants Error: {e}\")\n    sys.exit(1)\n\nprint(\"\\n📊 Available Data Sources:\", DataSource.all_sources())\nprint(\"⚠️  Note: TCBS is deprecated, use VCI or KBS instead\")\nprint(\"🆕 KBS is now available in v3.4.0\")\nprint(\"⏱️ Available TimeFrames:\", [t.value for t in TimeFrame])\nprint(\"\\n✅ All checks passed!\")\n```\n\nChạy test:\n\n```bash\npython test_installation.py\n```\n\n### 2. Quick Test\n\n```python\n# quick_test.py\nfrom vnstock import Quote, Listing\nfrom vnstock.core.types import TimeFrame\n\nprint(\"Testing Quote...\")# Khởi tạo với KBS (khuyến nghị)\nquote = Quote(source=\"KBS\", symbol=\"VCI\")\nprint(f\"✅ Quote initialized: {quote}\")\n\nprint(\"\\nTesting Listing...\")\nlisting = Listing(source=\"KBS\")\nprint(f\"✅ Listing initialized: {listing}\")\n\nprint(\"\\n✅ Installation successful!\")\n```\n\n## 🐛 Troubleshooting\n\n### Issue 1: `ModuleNotFoundError: No module named 'vnstock'`\n\n**Giải pháp:**\n\n```bash\n# Cài đặt lại\npip uninstall vnstock -y\npip install vnstock\n```\n\n### Issue 2: `ModuleNotFoundError: No module named 'pandas'`\n\n**Giải pháp:**\n\n```bash\n# Cài dependencies\npip install pandas requests beautifulsoup4 lxml pydantic tenacity\n\n# Hoặc cài toàn bộ\npip install vnstock --upgrade\n```\n\n### Issue 3: `ImportError: cannot import name 'Quote'`\n\n**Giải pháp:**\n\n```python\n# ✅ Đúng cách import\nfrom vnstock import Quote, Listing, Company\n\n# ❌ Sai cách\nfrom vnstock.Quote import Quote  # Không cần như này\n```\n\n### Issue 4: Network/Connection Errors\n\n**Lỗi:**\n```\nrequests.exceptions.ConnectionError: \nFailed to establish a new connection\n```\n\n**Giải pháp:**\n\n```python\nfrom vnstock import Quote\nfrom vnstock.config import Config\n\n# Tăng timeout\nConfig.TIMEOUT = 60\n\n# Hoặc sử dụng proxy\nquote = Quote(\n    source=\"vci\",\n    symbol=\"VCI\",\n    proxy=\"http://your-proxy:port\"\n)\n```\n\n### Issue 5: Rate Limit / 429 Error\n\n**Lỗi:**\n```\nHTTPError: 429 Too Many Requests\n```\n\n**Giải pháp:**\n\n**Cách 1: Đăng ký API key miễn phí**\n\n```python\nfrom vnstock.core.utils.auth import register_user\n\n# Đăng ký để tăng từ 20 lên 60 requests/phút\nregister_user()\n```\n\n**Cách 2: Tăng retry và delay**\n\n```python\nfrom vnstock.config import Config\nimport time\n\n# Tăng delay giữa requests\nConfig.RETRIES = 5\nConfig.BACKOFF_MULTIPLIER = 3\n\n# Hoặc thêm delay thủ công\ndef safe_request(func, *args, **kwargs):\n    try:\n        return func(*args, **kwargs)\n    except Exception as e:\n        if \"429\" in str(e):\n            time.sleep(5)  # Chờ 5 giây rồi thử lại\n            return func(*args, **kwargs)\n        raise\n\nresult = safe_request(quote.history, symbol=\"VCI\", start_date=\"2024-01-01\")\n```\n\n## 📖 Project Structure\n\nThư mục tiêu chuẩn khi làm việc với vnstock:\n\n```\nmy_project/\n├── .env                      # Cấu hình & API keys\n├── .gitignore               # Bỏ qua .env khi commit\n├── requirements.txt         # Dependencies\n├── main.py                  # Code chính\n├── data/                    # Lưu dữ liệu\n│   └── cache/              # Cache dữ liệu\n├── logs/                    # Log files\n└── tests/\n    └── test_vnstock.py      # Unit tests\n```\n\n### Ví dụ requirements.txt\n\n```\nvnstock>=3.4.0\nvnai>=2.3.9\npandas>=1.3.0\nnumpy>=1.20.0\nmatplotlib>=3.3.0\npython-dotenv>=0.19.0\n```\n\n### Ví dụ .gitignore\n\n```\n# Python\n__pycache__/\n*.py[cod]\n*$py.class\n*.so\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# Environment\n.env\n.venv\nenv/\nvenv/\nENV/\n\n# IDE\n.vscode/\n.idea/\n*.swp\n*.swo\n\n# Data\ndata/\n*.csv\n*.xlsx\nlogs/\n\n# Cache\n.cache/\n*.pyc\n```\n\n## 🚀 Getting Started - Ví dụ Đơn Giản\n\n### Ví dụ 1: Lấy Danh Sách Cổ Phiếu\n\n```python\n# example1_list_symbols.py\nfrom vnstock import Listing\n\n# Khởi tạo với KBS (khuyến nghị)\nlisting = Listing(source=\"KBS\")\n\n# Lấy tất cả mã chứng khoán\nall_symbols = listing.all_symbols(to_df=True)\nprint(f\"Tổng số mã: {len(all_symbols)}\")\nprint(all_symbols.head())\n\n# Lấy theo sàn\nhose_symbols = listing.symbols_by_exchange(exchange=\"HOSE\")\nprint(f\"\\nTổng mã HOSE: {len(hose_symbols)}\")\nprint(hose_symbols[:10])\n\n# Lấy theo chỉ số\nvn30_symbols = listing.symbols_by_group(group=\"VN30\")\nprint(f\"\\nTổng mã VN30: {len(vn30_symbols)}\")\nprint(vn30_symbols)\n```\n\nChạy:\n\n```bash\npython example1_list_symbols.py\n```\n\n### Ví dụ 2: Lấy Giá Lịch Sử\n\n```python\n# example2_price_history.py\nfrom vnstock import Quote\nfrom vnstock.core.types import TimeFrame\n\n# Khởi tạo với KBS (khuyến nghị)\nquote = Quote(source=\"KBS\", symbol=\"VCI\")\n\n# Lấy giá lịch sử\ndf = quote.history(\n    start_date=\"2024-01-01\",\n    end_date=\"2024-12-31\",\n    resolution=TimeFrame.DAILY\n)\n\nprint(\"Giá lịch sử:\")\nprint(df.head())\nprint(f\"\\nTổng cộng: {len(df)} ngày\")\nprint(f\"Giá cao nhất: {df['high'].max()}\")\nprint(f\"Giá thấp nhất: {df['low'].min()}\")\nprint(f\"Khối lượng trung bình: {df['volume'].mean():,.0f}\")\n```\n\n### Ví dụ 3: Lấy Thông Tin Công Ty\n\n```python\n# example3_company_info.py\nfrom vnstock import Company\n\n# Khởi tạo với KBS (khuyến nghị)\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\n\n# Lấy thông tin công ty\noverview = company.overview()\nprint(\"Thông tin công ty:\")\nprint(overview)\n\n# Lấy cổ đông chính\nshareholders = company.shareholders()\nprint(\"\\nCổ đông chính:\")\nprint(shareholders)\n\n# Lấy nhân viên quản lý\nofficers = company.officers()\nprint(\"\\nNhân viên quản lý:\")\nprint(officers)\n```\n\n## 📚 Các Bước Tiếp Theo\n\n1. ✅ **Installation** - Bạn đã ở đây\n2. [01-Overview](01-overview.md) - Tổng quan thư viện\n3. [03-Listing API](03-listing-api.md) - Tìm kiếm chứng khoán\n4. [04-Quote & Price](04-quote-price-api.md) - Giá lịch sử & realtime\n5. [05-Financial API](05-financial-api.md) - Dữ liệu tài chính\n6. [06-Connector Guide](06-connector-guide.md) - API bên ngoài\n7. [07-Best Practices](07-best-practices.md) - Mẹo & kinh nghiệm\n\n---\n\n**Last Updated**: 2024-12-17  \n**Version**: 3.4.0  \n**Status**: Actively Maintained  \n**Important**: TCBS deprecated, use VCI or KBS instead\n\nFile v1.0.3:references/vnstock/03-listing-api.md\n\n# 03 - Listing API - Tìm Kiếm & Lọc Chứng Khoán\n\n## 📖 Giới Thiệu\n\nListing API cung cấp các phương thức tìm kiếm, lọc và lấy thông tin về các chứng khoán có sẵn trên thị trường. Dữ liệu bao gồm:\n\n- Danh sách tất cả mã chứng khoán\n- Lọc theo sàn giao dịch (HOSE, HNX, UPCOM)\n- Lọc theo ngành công nghiệp (ICB)\n- Lọc theo chỉ số (VN30, VNMID, VNSML, etc.)\n- Futures, Bonds, Warrants, Funds\n- Industries & Sector classification\n\n## 🔌 So Sánh Nguồn Dữ Liệu\n\n| Method | KBS | VCI | Ghi Chú |\n|--------|-----|-----|---------|\n| **all_symbols()** | ✅ | ✅ | Cấu trúc giống nhau |\n| **symbols_by_exchange()** | ✅ | ✅ | KBS 6 columns, VCI 7 columns |\n| **symbols_by_industries()** | ✅ | ✅ | KBS 3 columns, VCI 10 columns |\n| **symbols_by_group()** | ✅ | ✅ | Cả hai đều trả về Series |\n| **industries_icb()** | ✅ | ✅ | KBS có thể rỗng, VCI đầy đủ |\n| **all_future_indices()** | ✅ | ✅ | Cả hai đều Series |\n| **all_government_bonds()** | ✅ | ✅ | Cả hai đều Series |\n| **all_covered_warrant()** | ✅ | ✅ | Cả hai đều Series |\n| **all_bonds()** | ✅ | ✅ | Cả hai đều Series |\n| **all_etf()** | ✅ | ❌ | **KBS độc quyền** |\n| **get_supported_groups()**  | ✅ | ❌ | **KBS độc quyền** |\n| **all_indices()** | ✅ | ✅ | chung |\n| **indices_by_group()** | ✅ | ✅ | chung |\n\n**Tổng số methods:**\n- **KBS**: 12 methods\n- **VCI**: 13 methods\n\n**Khuyến nghị:**\n- **KBS**: Ổn định hơn cho Google Colab/Kaggle\n- **VCI**: Dữ liệu đầy đủ hơn, có ICB classification và indices\n\n## 🏗️ Khởi Tạo\n\n```python\nfrom vnstock import Listing\n\n# Khởi tạo Listing adapter\n# Hỗ trợ KBS, VCI, MSN\nlisting = Listing(\n    source=\"vci\",           # Nguồn dữ liệu (khuyến nghị)\n    random_agent=False      # Sử dụng random user agent\n)\n\n# Hoặc với KBS (mới trong v3.4.0)\nlisting_kbs = Listing(source=\"kbs\")\n\n# ⚠️ TCBS đã deprecated, không nên sử dụng\n# listing_tcbs = Listing(source=\"tcbs\")  # DeprecatedWarning sẽ hiện ra\n```\n\n## 📋 Các Phương Thức\n\n### 1. all_symbols() - Tất Cả Mã Chứng Khoán\n\nLấy danh sách tất cả mã chứng khoán.\n\n**Parameters:**\n\n```\n- to_df (bool): Trả về DataFrame (default: True)\n- lang (str): Ngôn ngữ ('vi' hoặc 'en')\n```\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\nlisting = Listing(source=\"KBS\")\n\n# Trả về DataFrame\ndf = listing.all_symbols(to_df=True)\nprint(f\"Shape: {df.shape}\")  # (1565, 2)\nprint(f\"Columns: {list(df.columns)}\")\nprint(f\"Dtypes:\\n{df.dtypes}\")\n# Output:\n# Shape: (1565, 2)\n# Columns: ['symbol', 'organ_name']\n# Dtypes:\n# symbol        object\n# organ_name    object\ndf.head()\n# Output với KBS:\n#   symbol          organ_name\n# 0    DPP  CTCP Dược Đồng Nai\n# 1    SDA  CTCP Simco Sông Đà\n\n# Trả về list\nsymbols = listing.all_symbols(to_df=False)\nprint(f\"Type: {type(symbols)}\")  # <class 'list'>\nprint(f\"Length: {len(symbols)}\")  # 1565\nprint(symbols[:10])\n# Output: ['DPP', 'SDA', 'SDC', 'SDH', 'SDS', 'SDT', 'SDV', 'SDW', 'SDY', 'SDZ']\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\nlisting = Listing(source=\"VCI\")\n\n# Trả về DataFrame\ndf = listing.all_symbols(to_df=True)\nprint(f\"Shape: {df.shape}\")  # (1733, 2)\nprint(f\"Columns: {list(df.columns)}\")\nprint(f\"Dtypes:\\n{df.dtypes}\")\n# Output:\n# Shape: (1733, 2)\n# Columns: ['symbol', 'organ_name']\n# Dtypes:\n# symbol        object\n# organ_name    object\ndf.head()\n# Output với VCI:\n#   symbol                                         organ_name\n# 0    YTC  Công ty Cổ phần Xuất nhập khẩu Y tế Thành phố ...\n# 1    YEG                     Công ty Cổ phần Tập đoàn Yeah1\n\n# Trả về list\nsymbols = listing.all_symbols(to_df=False)\nprint(f\"Length: {len(symbols)}\")  # 1733\nprint(symbols[:10])\n# Output: ['YTC', 'YEG', 'YBM', 'YBC', 'XPH', 'XDC', 'XDC1', 'XDA', 'XDA1', 'XDG']\n```\n\n### 2. symbols_by_exchange() - Lọc Theo Sàn\n\nLấy danh sách mã chứng khoán theo sàn giao dịch.\n\n**Parameters:**\n\n```\n- exchange (str): Sàn giao dịch\n  ├─ 'HOSE': Sở giao dịch Hà Nội (HOSE) - Thị trường chính\n  ├─ 'HNX': Sở giao dịch Hà Nội (HNX) - Thị trường phụ\n  └─ 'UPCOM': Chứng khoán chưa niêm yết (UPCOM)\n- lang (str): Ngôn ngữ ('vi' hoặc 'en')\n```\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\nlisting = Listing(source=\"KBS\")\n\n# Lấy các mã HOSE\nhose_symbols = listing.symbols_by_exchange(exchange=\"HOSE\", to_df=True)\nprint(f\"Shape: {hose_symbols.shape}\")  # (1952, 6)\nprint(f\"Columns: {list(hose_symbols.columns)}\")\nprint(f\"Dtypes:\\n{hose_symbols.dtypes}\")\n# Output:\n# Shape: (1952, 6)\n# Columns: ['symbol', 'organ_name', 'en_organ_name', 'exchange', 'type', 'id']\n# Dtypes:\n# symbol           object\n# organ_name       object\n# en_organ_name    object\n# exchange         object\n# type             object\n# id                int64\nprint(hose_symbols[['symbol', 'exchange', 'type']].head())\n# Output với KBS:\n#   symbol exchange   type  id\n# 0    DPP    UPCOM  stock   1\n# 1    SDA      HNX  stock   1\n\n# Lấy các mã HNX\nhnx_symbols = listing.symbols_by_exchange(exchange=\"HNX\", to_df=True)\nprint(f\"HNX symbols: {len(hnx_symbols)}\")\n\n# Lấy các mã UPCOM\nupcom_symbols = listing.symbols_by_exchange(exchange=\"UPCOM\", to_df=True)\nprint(f\"UPCOM symbols: {len(upcom_symbols)}\")\n\n# Chỉ lấy list symbols\nhose_list = listing.symbols_by_exchange(exchange=\"HOSE\", to_df=False)\nprint(f\"Type: {type(hose_list)}\")  # <class 'list'>\nprint(f\"First 10: {hose_list[:10]}\")\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\nlisting = Listing(source=\"VCI\")\n\n# Lấy các mã HOSE\nhose_symbols = listing.symbols_by_exchange(exchange=\"HOSE\", to_df=True)\nprint(f\"Shape: {hose_symbols.shape}\")  # (3210, 7)\nprint(f\"Columns: {list(hose_symbols.columns)}\")\nprint(f\"Dtypes:\\n{hose_symbols.dtypes}\")\n# Output:\n# Shape: (3210, 7)\n# Columns: ['symbol', 'exchange', 'type', 'organ_short_name', 'organ_name', 'product_grp_id', 'icb_code2']\n# Dtypes:\n# symbol              object\n# exchange            object\n# type                object\n# organ_short_name    object\n# organ_name          object\n# product_grp_id      object\n# icb_code2           object\nprint(hose_symbols[['symbol', 'exchange', 'type']].head())\n# Output với VCI:\n#   symbol exchange   type organ_short_name                                         organ_name product_grp_id icb_code2\n# 0    YTC    UPCOM  STOCK  XNK Y tế TP.HCM  Công ty Cổ phần Xuất nhập khẩu Y tế Thành phố ...            UPX      4500\n# 1    YEG      HSX  STOCK   Tập đoàn Yeah1                     Công ty Cổ phần Tập đoàn Yeah1            STO      5500\n\n# Chỉ lấy list symbols\nhose_list = listing.symbols_by_exchange(exchange=\"HOSE\", to_df=False)\nprint(f\"Type: {type(hose_list)}\")  # <class 'list'>\nprint(f\"First 10: {hose_list[:10]}\")\n```\n\n**Kiến Thức Nâng Cao:**\n\n```python\n# Đếm mã theo sàn\nfrom collections import Counter\n\nall_df = listing.all_symbols(to_df=True)\nexchange_counts = all_df['exchange'].value_counts()\nprint(exchange_counts)\n# Output:\n# HOSE     1020\n# HNX      140\n# UPCOM     80\n# Name: exchange, dtype: int64\n\n# So sánh giữa các sàn\nhose_df = all_df[all_df['exchange'] == 'HOSE']\nhnx_df = all_df[all_df['exchange'] == 'HNX']\n\nprint(f\"HOSE industries: {hose_df['industry'].nunique()}\")\nprint(f\"HNX industries: {hnx_df['industry'].nunique()}\")\n```\n\n### 3. symbols_by_industries() - Lọc Theo Ngành\n\nLấy danh sách mã chứng khoán theo ngành công nghiệp.\n\n**Parameters:**\n\n```\n- to_df (bool): Trả về DataFrame\n- lang (str): Ngôn ngữ\n```\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\nlisting = Listing(source=\"KBS\")\n\n# Lọc theo ngành cụ thể\nbanking_df = listing.symbols_by_industries(industry_name='Ngân hàng', to_df=True)\nprint(f\"Total Banking stocks: {len(banking_df)}\")\nprint(banking_df.head())\n# Output với KBS:\n# Total Banking stocks: 697\n#   symbol  industry_code           industry_name\n# 0    ABR              6  Công nghệ và thông tin\n# 1    ADC              6  Công nghệ và thông tin\n# 2    BED              6  Công nghệ và thông tin\n# 3    CKV              6  Công nghệ và thông tin\n# 4    CMG              6  Công nghệ và thông tin\n\n# Lấy tất cả các ngành (không lọc)\nall_industries = listing.symbols_by_industries(to_df=True)\nprint(f\"Total symbols with industry: {len(all_industries)}\")\nprint(all_industries.head())\n# Output:\n#   symbol  industry_code           industry_name\n# 0    MGC              1  Nông nghiệp - lâm nghiệp và thủy sản\n# 1    GVT              1  Nông nghiệp - lâm nghiệp và thủy sản\n# 2    SWC              1  Nông nghiệp - lâm nghiệp và thủy sản\n# 3    SLD              1  Nông nghiệp - lâm nghiệp và thủy sản\n# 4    VID              1  Nông nghiệp - lâm nghiệp và thủy sản\n\n# Lấy danh sách các ngành duy nhất\nunique_industries = all_industries['industry_name'].unique()\nprint(f\"Total industries: {len(unique_industries)}\")\nprint(f\"First 10 industries: {list(unique_industries[:10])}\")\n# Output: Total industries: 28\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\nlisting = Listing(source=\"VCI\")\n\n# Lọc theo ngành cụ thể\nbanking_df = listing.symbols_by_industries(lang='vi', to_df=True)\nprint(f\"Total Banking stocks: {len(banking_df)}\")\nprint(banking_df.head())\n# Output với VCI:\n# Total Banking stocks: 35\n#   symbol                                         organ_name                   icb_name3  ... icb_code2 icb_code3 icb_code4\n# 0    STB                      Ngân hàng TMCP Sài Gòn                     Ngân hàng  ...      8000      8350      8353\n# 1    TCB                      Ngân hàng TMCP Kỹ thương Việt Nam                 Ngân hàng  ...      8000      8350      8353\n# 2    CTG                      Ngân hàng TMCP Công thương Việt Nam                 Ngân hàng  ...      8000      8350      8353\n\n# Lấy tất cả các ngành (không lọc)\nall_industries = listing.symbols_by_industries(lang='vi', to_df=True)\nprint(f\"Total symbols with industry: {len(all_industries)}\")\nprint(f\"Total industries: {len(all_industries)}\")\nindustries = listing.symbols_by_industries(to_df=True)\nunique_industries = industries['industry_name'].unique()\nprint(f\"Total industries: {len(unique_industries)}\")\nprint(unique_industries)\n\n# Top 5 ngành có nhiều mã nhất\nindustry_counts = industries['industry_name'].value_counts().head(5)\nprint(industry_counts)\n# Output:\n# Finance           200\n# Technology        150\n# Real Estate       120\n# ...\n\n# Lấy thông tin chi tiết về các ngành ICB (Industry Classification Benchmark) - chỉ hỗ trợ với VCI.\n# Parameters:\n# - lang (str): Ngôn ngữ\n# Ví dụ (với VCI):\n# Top 5 ngành có nhiều mã nhất\ntop_5 = industry_counts.head(5)\nprint(top_5)\n```\n\n### 4. industries_icb() - Phân Loại ICB\n\n⚠️ **Lưu ý với KBS**: KBS không cung cấp ICB classification. Sử dụng `symbols_by_industries()` để lấy mã theo ngành.\n\nLấy thông tin chi tiết về các ngành ICB (Industry Classification Benchmark) - chỉ hỗ trợ với VCI.\n\n**Parameters:**\n\n```\n- lang (str): Ngôn ngữ\n```\n\n**Ví dụ (với VCI):**\n\n```python\n# Sử dụng VCI cho ICB\nlisting_vci = Listing(source=\"vci\")\n\n# Lấy danh sách ICB\nicb_df = listing_vci.industries_icb()\nprint(icb_df.head())\n# Output:\n#   icb_id  icb_code  icb_name            super_group\n# 0  6001    1000     Oil & Gas           Energy\n# 1  6002    1001     Coal                Energy\n# 2  6003    1010     Alternative Energy Energy\n# ...\n\n# Thong tin chi tiet\nprint(f\"Total ICB categories: {len(icb_df)}\")\nprint(f\"Columns: {icb_df.columns.tolist()}\")\n\n# Tim theo super_group\nenergy = icb_df[icb_df['super_group'] == 'Energy']\nprint(f\"Energy sectors: {energy['icb_name'].tolist()}\")\n```\n\n**Lỗi với KBS:**\n\n```python\n# ❌ Sẽ gây lỗi với KBS\ntry:\n    icb_df = listing.industries_icb()\nexcept NotImplementedError as e:\n    print(f\"Lỗi: {e}\")\n# Output: Lỗi: KBS không cung cấp ICB classification. Sử dụng symbols_by_industries() để lấy mã theo ngành.\n```\n\n**Kiến Thức:**\n\n```python\n# Lấy danh sách các super_group\nsuper_groups = icb_df['super_group'].unique()\nprint(f\"Total super_groups: {len(super_groups)}\")\nfor group in super_groups:\n    sectors = icb_df[icb_df['super_group'] == group]\n    print(f\"{group}: {len(sectors)} sectors\")\n```\n\n### 5. symbols_by_group() - Lọc Theo Chỉ Số\n\nLấy danh sách mã chứng khoán theo chỉ số (Index Group).\n\n**Parameters:**\n\n```\n- group (str): Tên chỉ số\n  ├─ VN30, VN100, VNMID, VNSML, VNALL, VNSI\n  ├─ VNIT, VNIND, VNCONS, VNCOND, VNHEAL, VNENE\n  ├─ VNUTI, VNREAL, VNFIN, VNMAT\n  ├─ VNDIAMOND, VNFINLEAD, VNFINSELECT\n  └─ VNX50, VNXALL\n```\n\n**Ví dụ:**\n\n```python\n# VN30 - 30 cổ phiếu vốn hóa lớn nhất\nvn30 = listing.symbols_by_group(group_name=\"VN30\", to_df=True)\nprint(f\"VN30 symbols: {vn30['symbol'].tolist()}\")\n# Output với KBS:\n# VN30 symbols: ['ACB', 'BCM', 'BID', 'CTG', 'DGC', 'FPT', 'GAS', 'GVR', 'HDB', 'HPG', \n#                'LPB', 'MBB', 'MSN', 'MWG', 'PLX', 'SAB', 'SHB', 'SSB', 'SSI', 'STB', \n#                'TCB', 'TPB', 'VCB', 'VHM', 'VIB', 'VIC', 'VJC', 'VNM', 'VPB', 'VRE']\nprint(f\"Total VN30: {len(vn30)}\")\n# Output: Total VN30: 30\n\n# HNX30 - 30 cổ phiếu trên HNX\nhnx30 = listing.symbols_by_group(group_name=\"HNX30\", to_df=True)\nprint(f\"HNX30 symbols: {hnx30['symbol'].tolist()}\")\n# Output với KBS:\n# HNX30 symbols: ['BVS', 'CAP', 'CEO', 'DHT', 'DP3', 'DTD', 'DVM', 'DXP', 'HGM', 'HUT', \n#                 'IDC', 'IDV', 'L14', 'L18', 'LAS', 'LHC', 'MBS', 'NTP', 'PLC', 'PSD', \n#                 'PVB', 'PVC', 'PVI', 'PVS', 'SHS', 'SLS', 'TMB', 'TNG', 'VC3', 'VCS']\nprint(f\"Total HNX30: {len(hnx30)}\")\n# Output: Total HNX30: 30\n\n# Chỉ lấy list symbols\nvn30_list = listing.symbols_by_group(group_name=\"VN30\", to_df=False)\nprint(f\"First 10 VN30: {vn30_list[:10]}\")\n# Output: First 10 VN30: ['ACB', 'BCM', 'BID', 'CTG', 'DGC', 'FPT', 'GAS', 'GVR', 'HDB', 'HPG']\n```\n\n**Kiến Thức Nâng Cao:**\n\n```python\nfrom vnstock.constants import INDEX_GROUPS\n\n# Lấy tất cả chỉ số\nall_groups = []\nfor group_category, indices in INDEX_GROUPS.items():\n    print(f\"{group_category}: {indices}\")\n    all_groups.extend(indices)\n\n# Lấy tất cả mã từ VN30 đến VN100\nvn30_symbols = set(listing.symbols_by_group(group=\"VN30\"))\nvn100_symbols = set(listing.symbols_by_group(group=\"VN100\"))\n\n# Mã ở VN100 nhưng không ở VN30\nvn31_to_100 = vn100_symbols - vn30_symbols\nprint(f\"VN31-100 symbols: {sorted(list(vn31_to_100))}\")\n```\n\n### 6. all_future_indices() - Futures\n\nLấy danh sách tất cả hợp đồng tương lai.\n\n**Ví dụ:**\n\n```python\n# Lấy danh sách futures\nfutures_df = listing.all_future_indices()\nprint(futures_df.head())\n# Output:\n#   symbol  contract_name  maturity_date\n# 0   VNI   VN Index Futures  2024-12-31\n# 1   VI1   VN30 Dec24        2024-12-31\n# ...\n\nprint(f\"Total futures: {len(futures_df)}\")\n```\n\n### 7. all_government_bonds() - Trái Phiếu Chính Phủ\n\nLấy danh sách trái phiếu chính phủ.\n\n**Ví dụ:**\n\n```python\n# Lấy danh sách trái phiếu\nbonds_df = listing.all_government_bonds()\nprint(bonds_df.head())\n# Output:\n#   symbol  bond_name  maturity_date  coupon\n# 0  GB01   10Y Bond   2030-01-01     5.5%\n# ...\n```\n\n### 8. all_covered_warrant() - Warrant\n\nLấy danh sách warrant được phủ (Covered Warrant).\n\n**Ví dụ:**\n\n```python\n# Lấy danh sách warrant\nwarrants_df = listing.all_covered_warrant()\nprint(warrants_df[['symbol', 'underlying', 'expiry_date']].head())\n```\n\n### 9. all_bonds() - Trái Phiếu Doanh Nghiệp\n\nLấy danh sách trái phiếu doanh nghiệp.\n\n**Ví dụ:**\n\n```python\n# Lấy danh sách corporate bonds\nbonds_df = listing.all_bonds()\nprint(bonds_df[['symbol', 'issuer', 'coupon', 'maturity']].head())\n```\n\n## 🔄 Kết Hợp & Lọc Nâng Cao\n\n### Ví dụ 1: Cổ Phiếu Lớn ở Ngành Tài Chính\n\n```python\nimport pandas as pd\nfrom vnstock import Listing\n\nlisting = Listing(source=\"vci\")\n\n# Lấy dữ liệu\nall_symbols = listing.all_symbols(to_df=True)\nindustries = listing.symbols_by_industries(to_df=True)\n\n# Kết hợp dữ liệu\nmerged = all_symbols.merge(industries, on='symbol', how='left')\n\n# Lọc theo ngành Finance và sàn HOSE\nfinance_hose = merged[\n    (merged['industry'] == 'Finance') & \n    (merged['exchange'] == 'HOSE')\n]\n\nprint(f\"Finance stocks on HOSE: {len(finance_hose)}\")\nprint(finance_hose[['symbol', 'company_name']].head())\n```\n\n### Ví dụ 2: So Sánh VN30 vs VN31-100\n\n```python\n# Lấy dữ liệu\nvn30_set = set(listing.symbols_by_group(group=\"VN30\"))\nvn100_set = set(listing.symbols_by_group(group=\"VN100\"))\n\n# VN30\nprint(\"VN30 symbols:\")\nprint(sorted(vn30_set))\n\n# VN31-100 (ở VN100 nhưng không ở VN30)\nvn31_100 = sorted(vn100_set - vn30_set)\nprint(f\"\\nVN31-100 symbols ({len(vn31_100)} stocks):\")\nprint(vn31_100)\n\n# Lấy chi tiết của VN31-100\nall_df = listing.all_symbols(to_df=True)\nvn31_100_df = all_df[all_df['symbol'].isin(vn31_100)]\nprint(\"\\nVN31-100 details:\")\nprint(vn31_100_df[['symbol', 'company_name', 'industry']].to_string())\n```\n\n### Ví dụ 3: Ngành Công Nghệ\n\n```python\n# Lấy tất cả cổ phiếu IT\nvnit_symbols = listing.symbols_by_group(group=\"VNIT\")\nprint(f\"IT stocks ({len(vnit_symbols)}): {vnit_symbols}\")\n\n# Lấy chi tiết\nindustries_df = listing.symbols_by_industries(to_df=True)\nit_stocks = industries_df[industries_df['symbol'].isin(vnit_symbols)]\nprint(\"\\nIT stocks details:\")\nprint(it_stocks[['symbol', 'industry_name']].to_string())\n```\n\n### Ví dụ 4: Export Danh Sách\n\n```python\n# Export VN30\nvn30 = listing.symbols_by_group(group=\"VN30\")\nwith open('vn30_symbols.txt', 'w') as f:\n    for symbol in vn30:\n        f.write(symbol + '\\n')\n\n# Export tất cả cổ phiếu theo ngành\nindustries = listing.symbols_by_industries(to_df=True)\nindustries.to_excel('all_stocks_by_industry.xlsx', index=False)\n\n# Export VN100 chi tiết\nall_df = listing.all_symbols(to_df=True)\nvn100_symbols = listing.symbols_by_group(group=\"VN100\")\nvn100_df = all_df[all_df['symbol'].isin(vn100_symbols)]\nvn100_df.to_csv('vn100_details.csv', index=False)\n\nprint(\"✅ Exported successfully!\")\n```\n\n## � Methods Độc Quyền\n\n### 1. get_supported_groups() - Danh Sách Nhóm Hỗ Trợ (Chỉ KBS)\n\nLấy danh sách tất cả các nhóm được hỗ trợ bởi KBS.\n\n**Ví dụ:**\n```python\n# Khởi tạo với KBS\nlisting = Listing(source=\"KBS\")\n\n# Lấy danh sách nhóm hỗ trợ\nsupported_groups = listing.get_supported_groups()\nprint(f\"Shape: {supported_groups.shape}\")  # (16, 4)\nprint(f\"Columns: {list(supported_groups.columns)}\")\nprint(f\"Dtypes:\\n{supported_groups.dtypes}\")\n# Output:\n# Shape: (16, 4)\n# Columns: ['group_name', 'group_code', 'category', 'description']\n# Dtypes:\n# group_name     object\n# group_code     object\n# category       object\n# description    object\nprint(supported_groups[['group_name', 'category']].head())\n```\n\n**Output với KBS:**\n```\n  group_name       category\n0       BOND     Trái phiếu\n1         CW    Chứng quyền\n2        ETF        ETF/Quỹ\n3   FU_INDEX      Phái sinh\n4        HNX  Sàn giao dịch\n```\n\n### 2. all_indices() - Tất Cả Chỉ Số (Hỗ trợ từ tất cả sources qua `Listing`)\n\nLấy danh sách tất cả các chỉ số tiêu chuẩn hóa với thông tin đầy đủ. Trước đây chỉ có trên VCI, từ phiên bản 3.4.1 hàm này đã được chuẩn hoá và có thể gọi từ bất kỳ adapter nào thông qua `Listing(source=...)`. Kết quả trả về là `pd.DataFrame` với các cột tiêu chuẩn: [`symbol`, `name`, `description`, `full_name`, `group`, `index_id`, `sector_id`] (nếu có).\n\n**Ví dụ (VCI):**\n```python\n# Khởi tạo với VCI\nlisting = Listing(source=\"VCI\")\n\nall_indices_vci = listing.all_indices()\nprint(f\"Shape: {all_indices_vci.shape}\")\nprint(all_indices_vci[['symbol', 'name', 'group']].head())\n```\n\n**Ví dụ (KBS):**\n```python\n# Khởi tạo với KBS\nlisting = Listing(source=\"KBS\")\n\nall_indices_kbs = listing.all_indices()\nprint(f\"Shape: {all_indices_kbs.shape}\")\nprint(all_indices_kbs[['symbol', 'name', 'group']].head())\n```\n\n**Lưu ý:**\n- Một số provider có thể không có đầy đủ `sector_id` hoặc metadata giống VCI; hàm sẽ trả về những chỉ số sẵn có và giữ định dạng chuẩn để thuận tiện cho phân tích.\n\n### 3. indices_by_group() - Chỉ Số Theo Nhóm (Hỗ trợ từ tất cả sources qua `Listing`)\n\nLấy danh sách chỉ số theo nhóm tiêu chuẩn hóa (ví dụ: các chỉ số HOSE, chỉ số ngành/sector). Hàm này hiện đã hỗ trợ gọi từ `Listing` với mọi `source` (ví dụ: `kbs`, `vci`, `msn`) và trả về dữ liệu đã được chuẩn hoá.\n\n**Tham số:**\n- `group` (str): Tên nhóm (VD: `'HOSE'`, `'Sector Indices'`, ...)\n\n**Ví dụ (HOSE từ KBS):**\n```python\n# Khởi tạo với KBS\nlisting = Listing(source=\"KBS\")\n\nindices = listing.indices_by_group(group=\"HOSE\")\nif indices is not None:\n    print(f\"Shape: {indices.shape}\")\n    print(indices[['symbol', 'name']].head())\nelse:\n    print(\"Không có dữ liệu cho nhóm này\")\n```\n\n**Ví dụ (HOSE từ VCI):**\n```python\n# Khởi tạo với VCI\nlisting = Listing(source=\"VCI\")\n\nindices = listing.indices_by_group(group=\"HOSE\")\nprint(indices[['symbol', 'name']].head())\n```\n\n**Lưu ý:**\n- Một số source có thể cung cấp các nhóm khác nhau; nếu không có dữ liệu cho `group` truyền vào, hàm có thể trả về `None`.\n\n## �📊 Performance & Caching\n\n### Caching Dữ Liệu\n\n```python\nimport pickle\nimport os\nfrom vnstock import Listing\n\nlisting = Listing(source=\"vci\")\n\nCACHE_FILE = 'listing_cache.pkl'\n\n# Lấy hoặc load từ cache\nif os.path.exists(CACHE_FILE):\n    with open(CACHE_FILE, 'rb') as f:\n        all_symbols = pickle.load(f)\n    print(\"✅ Loaded from cache\")\nelse:\n    all_symbols = listing.all_symbols(to_df=True)\n    with open(CACHE_FILE, 'wb') as f:\n        pickle.dump(all_symbols, f)\n    print(\"✅ Cached for next time\")\n\nprint(all_symbols.head())\n```\n\n### Batch Operations\n\n```python\n# Lấy dữ liệu một lần, dùng nhiều lần\nall_symbols = listing.all_symbols(to_df=True)\nindustries = listing.symbols_by_industries(to_df=True)\nicb = listing.industries_icb()\n\n# Lọc theo nhiều tiêu chí\nhose_df = all_symbols[all_symbols['exchange'] == 'HOSE']\nprint(f\"HOSE: {len(hose_df)}\")\n\nfinance_df = hose_df[hose_df['industry'] == 'Finance']\nprint(f\"HOSE Finance: {len(finance_df)}\")\n```\n\n## ❌ Các Lỗi Thường Gặp\n\n### Lỗi 1: ValueError - Invalid Source\n\n```python\n# ❌ Sai\nlisting = Listing(source=\"invalid\")\n\n# ✅ Đúng - KBS (khuyến nghị), VCI, MSN\nlisting = Listing(source=\"kbs\")  # Nguồn mới, ổn định\nlisting = Listing(source=\"vci\")  # Nguồn truyền thống\nlisting = Listing(source=\"msn\")  # Nguồn dữ liệu quốc tế, crypto\n\n# ⚠️ TCBS đã deprecated\n# listing = Listing(source=\"tcbs\")  # DeprecatedWarning\n```\n\n### Lỗi 2: NotImplementedError - ICB với KBS\n\n```python\n# ❌ KBS không hỗ trợ ICB\ntry:\n    icb_df = listing.industries_icb()\nexcept NotImplementedError as e:\n    print(f\"Lỗi: {e}\")\n    # Solution: Sử dụng symbols_by_industries() thay thế\n    industries = listing.symbols_by_industries()\n```\n\n### Lỗi 3: Network/Timeout\n\n```python\n# Tăng timeout\nfrom vnstock.config import Config\nConfig.TIMEOUT = 60\n\n# Hoặc retry\nfrom tenacity import retry, stop_after_attempt\n\n@retry(stop=stop_after_attempt(3))\ndef get_symbols():\n    return listing.all_symbols()\n```\n\n### Lỗi 4: Empty Result\n\n```python\n# Nếu không có dữ liệu\nsymbols = listing.symbols_by_group(group_name=\"INVALID_INDEX\")\nif not symbols or len(symbols) == 0:\n    print(\"⚠️ No symbols found for this group\")\n```\n\n## 📚 Bước Tiếp Theo\n\n1. [02-Installation](02-installation.md) - Cài đặt\n2. [01-Overview](01-overview.md) - Tổng quan\n3. ✅ **03-Listing API** - Bạn đã ở đây\n4. [04-Quote & Price](04-quote-price-api.md) - Giá lịch sử\n5. [05-Financial API](05-financial-api.md) - Dữ liệu tài chính\n6. [06-Connector Guide](06-connector-guide.md) - API bên ngoài\n7. [07-Best Practices](07-best-practices.md) - Mẹo & kinh nghiệm\n\n---\n\n**Last Updated**: 2024-12-17  \n**Version**: 3.4.0  \n**Status**: Actively Maintained  \n**Important**: KBS là nguồn dữ liệu mới được khuyến nghị, ổn định hơn VCI cho Google Colab/Kaggle\n\nFile v1.0.3:references/vnstock/04-company-api.md\n\n# 04 - Company API - Thông Tin Công Ty\n\n## 📖 Giới Thiệu\n\n**Company API** cung cấp thông tin chi tiết về các công ty cổ phần, bao gồm hồ sơ cơ bản, cấu trúc cổ đông, nhân viên quản lý, sự kiện công ty, và tin tức.\n\n## 🔌 So Sánh Nguồn Dữ Liệu\n\n| Method | KBS | VCI | Ghi Chú |\n|--------|-----|-----|---------|\n| **overview()** | ✅ | ✅ | KBS có 30 columns, VCI có 10 columns |\n| **shareholders()** | ✅ | ✅ | KBS trả về 1 dòng, VCI trả về nhiều dòng |\n| **officers()** | ✅ | ✅ | VCI có filter_by, KBS không |\n| **subsidiaries()** | ✅ | ✅ | Cấu trúc khác nhau |\n| **affiliate()** | ✅ | ✅ | Cả hai đều có |\n| **news()** | ✅ | ✅ | KBS có pagination, VCI không |\n| **events()** | ✅ | ✅ | KBS có thể rỗng, VCI đầy đủ |\n| **ownership()** | ✅ | ❌ | Chỉ KBS hỗ trợ |\n| **capital_history()** | ✅ | ❌ | Chỉ KBS hỗ trợ |\n| **insider_trading()** | ✅ | ❌ | Chỉ KBS hỗ trợ |\n| **reports()** | ❌ | ✅ | Chỉ VCI hỗ trợ |\n| **trading_stats()** | ❌ | ✅ | Chỉ VCI hỗ trợ |\n| **ratio_summary()** | ❌ | ✅ | Chỉ VCI hỗ trợ |\n\n**Khuyến nghị:**\n- **KBS**: Ổn định hơn cho Google Colab/Kaggle, có thêm dữ liệu insider trading\n- **VCI**: Dữ liệu đầy đủ hơn cho events, có financial reports và trading stats\n\n## 🔌 Nguồn Dữ Liệu\n\n| Nguồn | Hỗ Trợ | Ghi Chú |\n|-------|--------|--------|\n| **KBS** | ✅ | Web scraping - Khuyến nghị, ổn định |\n| VCI | ✅ | Web scraping - Nguồn truyền thống |\n| TCBS | ⚠️ | Web scraping - Deprecated, sẽ loại bỏ v3.5.0 |\n\n## 🚀 Bắt Đầu\n\n```python\nfrom vnstock import Company\n\n# Khởi tạo với KBS (khuyến nghị)\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\n\n# Xem thông tin cổ đông\nshareholders = company.shareholders()\nprint(shareholders)\n\n# Hoặc với VCI\ncompany_vci = Company(source=\"VCI\", symbol=\"VCI\")\n\n# ⚠️ TCBS đã deprecated, không nên sử dụng\n# company_tcbs = Company(source=\"TCBS\", symbol=\"VCI\")\n```\n\n## 📚 Phương Thức Chính\n\n### 1. overview() - Thông Tin Cơ Bản\n\nLấy thông tin tổng quan về công ty.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` (1 dòng) với các cột:\n- `symbol` - Mã chứng khoán\n- `issue_share` - Số cổ phiếu phát hành\n- `company_profile` - Hồ sơ công ty (JSON)\n- `icb_name2`, `icb_name3`, `icb_name4` - Phân loại ngành (ICB)\n- `financial_ratio_issue_share` - Thông tin tài chính\n- `charter_capital` - Vốn điều lệ\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\noverview = company.overview()\nprint(f\"Shape: {overview.shape}\")  # (1, 30)\nprint(f\"Columns: {list(overview.columns)}\")\nprint(f\"Dtypes:\\n{overview.dtypes}\")\n# Output:\n# Shape: (1, 30)\n# Columns: ['business_model', 'symbol', 'founded_date', 'charter_capital', \n#           'number_of_employees', 'listing_date', 'par_value', 'exchange', ...]\n# Dtypes:\n# business_model           object\n# symbol                   object\n# founded_date             object\n# charter_capital           int64\n# number_of_employees       int64\n# ...\nprint(overview[['symbol', 'charter_capital', 'exchange']].head())\n```\n\n**Output với KBS:**\n```\n                                      business_model symbol founded_date  charter_capital  exchange\n0  \\n- Môi giới chứng khoán và giao dịch cho vay ...    VCI   06/08/2007      8501000000000      HOSE\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\noverview = company.overview()\nprint(f\"Shape: {overview.shape}\")  # (1, 10)\nprint(f\"Columns: {list(overview.columns)}\")\nprint(f\"Dtypes:\\n{overview.dtypes}\")\n# Output:\n# Shape: (1, 10)\n# Columns: ['symbol', 'id', 'issue_share', 'history', 'company_profile', \n#           'icb_name3', 'icb_name2', 'icb_name4', 'financial_ratio_issue_share', 'charter_capital']\n# Dtypes:\n# symbol                         object\n# id                             object\n# issue_share                     int64\n# history                        object\n# ...\nprint(overview[['symbol', 'charter_capital', 'icb_name4']].head())\n```\n\n**Output với VCI:**\n```\n  symbol     id  issue_share  ...             icb_name4 charter_capital\n0    VCI  75885    850100000  ...  Môi giới chứng khoán   8501000000000\n```\n\n### 2. shareholders() - Cổ Đông Chính\n\nLấy danh sách các cổ đông lớn.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` với các cột:\n- `name` - Tên cổ đông (str)\n- `update_date` - Ngày cập nhật (str, format: \"YYYY-MM-DDTHH:MM:SS\")\n- `shares_owned` - Số cổ phiếu sở hữu (int64)\n- `ownership_percentage` - Tỷ lệ sở hữu (float64, %)\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nshareholders = company.shareholders()\nprint(shareholders.shape)  # (1, 4)\nprint(shareholders[['name', 'shares_owned', 'ownership_percentage']].head())\n```\n\n**Output với KBS:**\n```\n      name          update_date  shares_owned  ownership_percentage\n0  Tô Hải  2025-06-30T00:00:00     128889403                 17.95\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\nshareholders = company.shareholders()\nprint(shareholders.shape)  # (33, 5)\nprint(shareholders[['share_holder', 'quantity', 'share_own_percent']].head(3))\n```\n\n**Output với VCI:**\n```\n         id           share_holder   quantity  share_own_percent update_date\n0  96744105                 Tô Hải  129139403            0.17870  2025-10-31\n1  96742707         PYN Elite Fund    8132100            0.04910  2025-01-24\n2  96734076  Nguyễn Phan Minh Khôi    7483872            0.04591  2025-01-24\n```\n\n### 3. officers() - Ban lãnh đạo\n\nLấy danh sách ban lãnh đạo (Ban điều hành, Hội đồng quản trị).\n\n**Tham số:**\n- `filter_by` (str, tùy chọn): Loại lọc\n  - `\"all\"` - Tất cả (mặc định)\n  - `\"ceo\"` - Chỉ CEO\n  - `\"boc\"` - Board of Directors\n\n**Trả về:** `pd.DataFrame` với các cột:\n- `from_date` - Năm bắt đầu (int)\n- `position` - Vị trí công việc (str, VN)\n- `name` - Tên nhân viên (str)\n- `position_en` - Vị trí công việc (str, EN)\n- `owner_code` - Mã sở hữu (str)\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nofficers = company.officers()\nprint(officers.shape)  # (12, 5)\nprint(officers[['name', 'position', 'from_date']].head(3))\n```\n\n**Output với KBS:**\n```\n                   name        position  from_date\n0  Bà Nguyễn Thanh Phượng          CTHĐQT       2007\n1       Ông Đinh Quang Hoàn  TVHĐQT/Phó TGĐ       2007\n2                Ông Tô Hải      TGĐ/TVHĐQT       2007\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\nofficers = company.officers()\nprint(officers.shape)  # (14, 7)\nprint(officers[['officer_name', 'officer_position', 'officer_own_percent']].head(3))\n```\n\n**Output với VCI:**\n```\n   id         officer_name                            officer_position  officer_own_percent   quantity\n0  11               Tô Hải  Tổng Giám đốc/Thành viên Hội đồng Quản trị               0.1787  129139403\n1  14  Nguyễn Thanh Phượng                  Chủ tịch Hội đồng Quản trị               0.0318   22815000\n2   4     Nguyễn Quang Bảo                           Phó Tổng Giám đốc               0.0032    2324156\n```\n\n### 4. subsidiaries() - Công Ty Con\n\nLấy danh sách công ty con.\n\n**Tham số:**\n- `filter_by` (str, tùy chọn): \n  - `\"subsidiary\"` - Công ty con trực tiếp\n  - `\"all\"` - Tất cả\n\n**Trả về:** `pd.DataFrame` với các cột:\n- `update_date` - Ngày cập nhật (str, format: \"YYYY-MM-DDTHH:MM:SS\")\n- `name` - Tên công ty con (str)\n- `charter_capital` - Vốn điều lệ (int64)\n- `ownership_percent` - Tỷ lệ sở hữu (float64, %)\n- `currency` - Loại tiền tệ (str)\n- `type` - Loại quan hệ (str)\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nsubsidiaries = company.subsidiaries()\nprint(subsidiaries.shape)  # (1, 6)\nprint(subsidiaries[['name', 'charter_capital', 'ownership_percent']])\n```\n\n**Output với KBS:**\n```\n                                          name  charter_capital  ownership_percent\n0  CTCP Quản lý Quỹ Đầu tư Chứng khoán Bản Việt     130000000000                 51\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\ntry:\n    subsidiaries = company.subsidiaries()\n    print(subsidiaries.shape)\n    print(subsidiaries.head())\nexcept Exception as e:\n    print(f\"VCI subsidiaries error: {e}\")\n# Output: VCI subsidiaries error: RetryError[<Future...>]\n```\n\n### 5. affiliate() - Công Ty Liên Kết\n\nLấy danh sách công ty liên kết.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame`\n\n⚠️ **Lưu ý:** Phương thức này có thể trả về lỗi nếu không có dữ liệu\n\n### 6. news() - Tin Tức\n\nLấy tin tức gần đây về công ty.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` với các cột:\n- `head` - Tiêu đề tin (str)\n- `article_id` - ID bài viết (int64)\n- `publish_time` - Thời gian xuất bản (str, format: \"YYYY-MM-DDTHH:MM:SS\")\n- `url` - Liên kết tin tức (str)\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nnews = company.news()\nprint(news.shape)  # (1, 5)\nprint(news[['head', 'publish_time']].head())\n```\n\n**Output với KBS:**\n```\n                                           head  article_id           publish_time                                                url\n0  VCI- Thông báo về ngày đăng ký cuối cùng...    1386720  2025-12-31T14:03:26  /2025/12/vci-thong-bao-ve-ngay-dang-ky-cuoi-cu...\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\nnews = company.news()\nprint(news.shape)  # (10, 18)\nprint(news[['news_title', 'public_date', 'price_change_pct']].head(3))\n```\n\n**Output với VCI:**\n```\n        id                                         news_title  ...  price_change_pct\n0  9121667  VCI: Thông báo về việc giao dịch chứng khoán t...  ...        -0.013235\n1  9108930  VCI: Giấy phép điều chỉnh giấy phép thành lập ...  ...         0.019118\n2  9095781  VCI: Quyết định về việc thay đổi đăng ký niêm yết                 ...        -0.002825\n```\n\n### 7. events() - Sự Kiện Công Ty\n\nLấy danh sách sự kiện công ty (chia cổ tức, phát hành cổ phiếu, niêm yết, v.v.).\n\n⚠️ **Lưu ý với KBS**: Có thể không có dữ liệu sự kiện cho một số công ty.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` với các cột:\n- `id` - ID sự kiện\n- `event_title` - Tiêu đề sự kiện (str, VN)\n- `en__event_title` - Tiêu đề sự kiện (str, EN)\n- `public_date` - Ngày công bố (str)\n- `issue_date` - Ngày phát hành (str)\n- `source_url` - Liên kết tài liệu\n- `event_list_code` - Mã loại sự kiện (str)\n- `event_list_name` - Tên loại sự kiện (str, VN)\n- `en__event_list_name` - Tên loại sự kiện (str, EN)\n- `ratio` - Tỷ lệ (float64, VD: 0.35 = 35%)\n- `value` - Giá trị (float64)\n- `record_date` - Ngày ghi danh (str)\n- `exright_date` - Ngày hết quyền (str)\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nevents = company.events()\nprint(events.shape)  # (0, 0) - Có thể rỗng\n\n# Nếu không có dữ liệu với KBS, thử VCI\nif events.empty:\n    company_vci = Company(source=\"VCI\", symbol=\"VCI\")\n    events = company_vci.events()\n    print(f\"VCI events: {events.shape}\")\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\nevents = company.events()\nprint(events.shape)  # (32, 13)\nprint(events[['event_title', 'event_list_name', 'public_date']].head(5))\n```\n\n**Output với VCI:**\n```\n         id                                        event_title  ...           event_list_name en__event_list_name\n0   1868825  VCI - Trả cổ tức Đợt 1, 2021 bằng tiền 1200 VN...  ...  Trả cổ tức bằng tiền mặt       Cash Dividend\n1  16582552  VCI - Trả cổ tức Đợt 1 năm 2022 bằng tiền 700 ...  ...  Trả cổ tức bằng tiền mặt       Cash Dividend\n2  22322707  VCI - Trả cổ tức Đợt 2 năm 2022 bằng tiền 500 ...  ...  Trả cổ tức bằng tiền mặt       Cash Dividend\n3  42249237  VCI - Trả cổ tức Đợt 1 năm 2024 bằng tiền 400 ...  ...  Trả cổ tức bằng tiền mặt       Cash Dividend\n4  50556599  VCI - Trả cổ tức Đợt 2 năm 2024 bằng tiền 250 ...  ...  Trả cổ tức bằng tiền mặt       Cash Dividend\n```\n\n## 💡 Ví Dụ Thực Tế\n\n### Phân Tích Cấu Trúc Cổ Đông\n\n**Với KBS (khuyến nghị):**\n```python\nfrom vnstock import Company\n\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nshareholders = company.shareholders()\n\n# Top cổ đông lớn (KBS chỉ trả về 1 dòng)\ntop_shareholder = shareholders.nlargest(1, 'shares_owned')\nprint(\"Cổ đông lớn nhất:\")\nprint(top_shareholder[['name', 'shares_owned', 'ownership_percentage']])\n\n# Tính tỷ lệ sở hữu\ntotal_ownership = shareholders['ownership_percentage'].sum()\nprint(f\"\\nTổng tỷ lệ sở hữu: {total_ownership:.2f}%\")\n```\n\n**Với VCI (nguồn truyền thống):**\n```python\nfrom vnstock import Company\n\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\nshareholders = company.shareholders()\n\n# Top 5 cổ đông lớn\ntop_5 = shareholders.nlargest(5, 'quantity')\nprint(\"Top 5 cổ đông:\")\nprint(top_5[['share_holder', 'quantity', 'share_own_percent']])\n\n# Tính tập trung cổ đông\ntop_10_pct = shareholders.nlargest(10, 'share_own_percent')['share_own_percent'].sum()\nprint(f\"\\nTrong lượng cổ đông top 10: {top_10_pct:.2f}%\")\n```\n\n### Theo Dõi Ban Quản Trị\n\n```python\nfrom vnstock import Company\n\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nofficers = company.officers()\n\n# Các vị trí lãnh đạo\npositions = officers['position'].unique()\nprint(f\"Số lượng vị trí quản lý: {len(positions)}\")\nprint(f\"Các vị trí: {list(positions)}\")\n\n# Cổ đông nội bộ (có sở hữu cổ phiếu)\ninsiders = officers[officers['position'].str.contains('TGĐ|CTHĐQT|TVHĐQT', na=False)]\nprint(f\"\\nBan lãnh đạo: {len(insiders)} người\")\nprint(insiders[['name', 'position']])\n```\n\n### Theo Dõi Sự Kiện\n\n```python\nfrom vnstock import Company\n\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nevents = company.events()\n\n# Kiểm tra nếu có sự kiện\nif not events.empty:\n    # Sự kiện chia cổ tức\n    dividend_events = events[events['event_list_code'] == 'DIV']\n    print(f\"Số lần chia cổ tức: {len(dividend_events)}\")\n    \n    # Sự kiện phát hành cổ phiếu\n    issue_events = events[events['event_list_code'] == 'ISS']\n    print(f\"Số lần phát hành cổ phiếu: {len(issue_events)}\")\nelse:\n    print(\"Không có dữ liệu sự kiện với KBS, thử VCI:\")\n    company_vci = Company(source=\"VCI\", symbol=\"VCI\")\n    events = company_vci.events()\n    print(f\"VCI events: {events.shape}\")\n```\n\n### 8. ownership() - Cấu Trúc Cổ Đông (Chỉ KBS)\n\nLấy thông tin cơ cấu cổ đông theo tỷ lệ sở hữu - chỉ có ở KBS.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` với các cột:\n- `owner_type` - Loại cổ đông (str)\n- `ownership_percentage` - Tỷ lệ sở hữu (float64, %)\n- `shares_owned` - Số cổ phiếu sở hữu (int64)\n- `update_date` - Ngày cập nhật (str, format: \"YYYY-MM-DDTHH:MM:SS\")\n\n**Ví dụ:**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\nownership = company.ownership()\nprint(ownership.shape)  # (3, 4)\nprint(ownership)\n```\n\n**Output với KBS:**\n```\n                owner_type  ownership_percentage  shares_owned          update_date\n0     CĐ nắm trên 5% số CP                 17.95     128889403  2024-12-31T00:00:00\n1  CĐ nắm từ 1% - 5% số CP                 39.65     284754680  2024-12-31T00:00:00\n2     CĐ nắm dưới 1% số CP                 42.40     304455397  2024-12-31T00:00:00\n```\n\n### 9. capital_history() - Lịch Sử Vốn Điều Lệ (Chỉ KBS)\n\nLấy lịch sử thay đổi vốn điều lệ của công ty - chỉ có ở KBS.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` với các cột:\n- `date` - Ngày thay đổi (str, format: \"YYYY-MM-DD\")\n- `charter_capital` - Vốn điều lệ (int64)\n- `currency` - Loại tiền tệ (str)\n\n**Ví dụ:**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\ncapital_history = company.capital_history()\nprint(capital_history.shape)  # (19, 3)\nprint(capital_history.head())\n```\n\n**Output với KBS:**\n```\n        date  charter_capital currency\n0 2025-12-17    8501000000000      VND\n1 2025-03-07    7226000000000      VND\n2 2024-06-12    7180994800000      VND\n3 2024-10-10    5744694800000      VND\n4 2024-05-08    4419000000000      VND\n```\n\n### 10. insider_trading() - Giao Dịch Nội Bộ (Chỉ KBS)\n\nLấy thông tin giao dịch của người nội bộ - chỉ có ở KBS.\n\n**Tham số:**\n- `page` (int, tùy chọn): Số trang (mặc định: 1)\n- `page_size` (int, tùy chọn): Kích thước trang (mặc định: 10)\n\n**Trả về:** `pd.DataFrame` (có thể rỗng)\n\n**Ví dụ:**\n```python\n# Khởi tạo với KBS\ncompany = Company(source=\"KBS\", symbol=\"VCI\")\ninsider_trading = company.insider_trading()\nprint(f\"Shape: {insider_trading.shape}\")\n# Output: Shape: (0, 0) - Có thể rỗng nếu không có dữ liệu\n```\n\n### 11. reports() - Báo Cáo Phân Tích (Chỉ VCI)\n\nLấy báo cáo phân tích về công ty - chỉ có ở VCI.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` (có thể rỗng)\n\n**Ví dụ:**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\nreports = company.reports()\nprint(f\"Shape: {reports.shape}\")\n# Output: Shape: (0, 0) - Có thể rỗng nếu không có báo cáo\n```\n\n### 12. trading_stats() - Thống Kê Giao Dịch (Chỉ VCI)\n\nLấy thống kê giao dịch của công ty - chỉ có ở VCI.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` với 24 columns bao gồm:\n- `symbol`, `exchange`, `ev`, `ceiling`, `floor`\n- `avg_match_volume_2w`, `foreign_holding_room`, `current_holding_ratio`\n- `max_holding_ratio`, và nhiều thống kê khác\n\n**Ví dụ:**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\ntrading_stats = company.trading_stats()\nprint(trading_stats.shape)  # (1, 24)\nprint(trading_stats[['symbol', 'exchange', 'ev', 'foreign_holding_room']].head())\n```\n\n**Output với VCI:**\n```\n  symbol exchange              ev  ceiling  foreign_holding_room\n0    VCI     HOSE  29498470000000    37250             144233070\n```\n\n### 13. ratio_summary() - Tóm Tắt Tỷ Lệ Tài Chính (Chỉ VCI)\n\nLấy tóm tắt các tỷ lệ tài chính của công ty - chỉ có ở VCI.\n\n**Tham số:** Không có\n\n**Trả về:** `pd.DataFrame` với 46 columns tài chính\n\n**Ví dụ:**\n```python\n# Khởi tạo với VCI\ncompany = Company(source=\"VCI\", symbol=\"VCI\")\nratio_summary = company.ratio_summary()\nprint(ratio_summary.shape)  # (1, 46)\nprint(ratio_summary[['symbol', 'year_report', 'revenue', 'ebit']].head())\n```\n\n**Output với VCI:**\n```\n  symbol  year_report        revenue          ebit\n0    VCI         2025  1443289075867  716139241499\n```\n\n```\n\n## ⚠️ Ghi Chú Quan Trọng\n\n1. **KBS là nguồn khuyến nghị**: Ổn định hơn VCI cho Google Colab/Kaggle\n2. **Dữ liệu không đầy đủ**: Không phải công ty nào cũng có đầy đủ thông tin cho tất cả phương thức\n3. **KBS hạn chế**: Events có thể rỗng, chỉ trả về 1 cổ đông lớn nhất\n4. **Giá trị NaN**: Nếu không có dữ liệu, sẽ trả về `NaN` hoặc rỗng\n5. **Phụ thuộc vào nguồn**: Thông tin khác nhau giữa KBS, VCI và TCBS\n6. **TCBS deprecated**: Sẽ loại bỏ trong v3.5.0, không nên sử dụng\n7. **Dữ liệu lịch sử**: Thông tin lịch sử được cập nhật định kỳ\n8. **Methods độc quyền**: KBS có ownership/capital_history/insider_trading, VCI có reports/trading_stats/ratio_summary\n\n## 🔗 Xem Thêm\n\n- **[03-Listing API](03-listing-api.md)** - Tìm kiếm chứng khoán\n- **[05-Trading API](05-trading-api.md)** - Dữ liệu giao dịch\n- **[06-Financial API](06-financial-api.md)** - Dữ liệu tài chính\n- **[08-Best Practices](08-best-practices.md)** - Mẹo tối ưu hóa\n\n---\n\n**Last Updated**: 2024-12-17  \n**Version**: 3.4.0  \n**Status**: Actively Maintained  \n**Important**: KBS là nguồn dữ liệu mới được khuyến nghị, ổn định hơn VCI cho Google Colab/Kaggle\n\nFile v1.0.3:references/vnstock/05-trading-api.md\n\n# 05 - Trading API - Dữ Liệu Giao Dịch\n\n## 📖 Giới Thiệu\n\n**Trading API** cung cấp dữ liệu giao dịch chi tiết: bảng giá real-time và mức bid/ask thị trường.\n\n## 🔌 So Sánh Nguồn Dữ Liệu\n\n| Method | KBS | VCI | Ghi Chú |\n|--------|-----|-----|---------|\n| **price_board()** | ✅ | ✅ | Cả hai đều có flat columns |\n\n**Tổng số methods:**\n- **KBS**: 1 method\n- **VCI**: 1 method\n\n**Khuyến nghị:**\n- **KBS**: Dữ liệu mới, áp dụng bộ tiêu chuẩn dữ liệu mới từ Vnstock, ổn định hơn và phù hợp cho sử dụng cả với Google Colab.\n- **VCI**: Dữ liệu cực kỳ chi tiết (77 columns), phù hợp cho phân tích sâu\n\n## 🚀 Bắt Đầu\n\n```python\nfrom vnstock import Trading\n\n# Khởi tạo với KBS (khuyến nghị)\ntrading_kbs = Trading(source=\"KBS\", symbol=\"VCI\")\n\n# Khởi tạo với VCI\ntrading_vci = Trading(source=\"VCI\", symbol=\"VCI\")\n\n# Lấy bảng giá thị trường\nboard_kbs = trading_kbs.price_board(symbols_list=['VCI', 'VCB', 'ACB'])\nboard_vci = trading_vci.price_board(symbols_list=['VCI', 'VCB', 'ACB'])\n```\n\n## 📚 Phương Thức Chính\n\n### 1. price_board() - Bảng Giá Real-Time\n\nLấy thông tin bảng giá của các mã chứng khoán theo thời gian thực.\n\n**Parameters:**\n\n**KBS:**\n```\n- symbols_list (List[str]): Danh sách mã chứng khoán\n- exchange (str): Sàn giao dịch ('HOSE', 'HNX', 'UPCOM') - Mặc định 'HOSE'\n- show_log (bool): Hiển thị log debug\n- get_all (bool): Lấy tất cả columns - Mặc định False\n```\n\n**VCI:**\n```\n- symbols_list (List[str]): Danh sách mã chứng khoán\n- show_log (bool): Hiển thị log debug\n```\n\n**Ví dụ:**\n\n**Với KBS (khuyến nghị):**\n```python\n# Khởi tạo với KBS\ntrading = Trading(source=\"KBS\", symbol=\"VCI\")\n\n# Lấy bảng giá (standard columns)\nboard = trading.price_board(symbols_list=['VCI', 'VCB', 'ACB'])\nprint(f\"Shape: {board.shape}\")  # (3, 28)\nprint(f\"Columns: {list(board.columns)}\")\nprint(f\"Dtypes:\\n{board.dtypes}\")\n# Output:\n# Shape: (3, 28)\n# Columns: ['symbol', 'exchange', 'ceiling_price', 'floor_price', 'reference_price',\n#           'open_price', 'high_price', 'low_price', 'close_price', 'average_price',\n#           'total_trades', 'total_value', 'price_change', 'percent_change',\n#           'bid_price_1', 'bid_vol_1', 'bid_price_2', 'bid_vol_2', 'bid_price_3', 'bid_vol_3',\n#           'ask_price_1', 'ask_vol_1', 'ask_price_2', 'ask_vol_2', 'ask_price_3', 'ask_vol_3',\n#           'foreign_buy_volume', 'foreign_sell_volume']\n# Dtypes:\n# symbol                  object\n# exchange                object\n# ceiling_price            int64\n# floor_price              int64\n# reference_price          int64\n# ...\nprint(board[['symbol', 'exchange', 'reference_price', 'price_change', 'percent_change']].head())\n```\n\n**Output với KBS:**\n```\n  symbol exchange  reference_price  price_change  percent_change\n0    VCI     HOSE            34850           -50         -0.1435\n1    VCB     HOSE            84500          100          0.1183\n2    ACB     HOSE            23450           -50         -0.2128\n```\n\n**Với VCI (nguồn chi tiết):**\n```python\n# Khởi tạo với VCI\ntrading = Trading(source=\"VCI\", symbol=\"VCI\")\n\n# Lấy bảng giá (flat columns)\nboard = trading.price_board(symbols_list=['VCI', 'VCB', 'ACB'])\nprint(f\"Shape: {board.shape}\")  # (3, 77)\nprint(f\"Columns sample: {list(board.columns)[:10]}...\")  # Flat columns\nprint(f\"Dtypes sample:\\n{board.dtypes.head(10)}\")\n# Output:\n# Shape: (3, 77)\n# Columns sample: ['symbol', 'ceiling', 'floor', 'ref_price', 'stock_type', 'exchange',\n#                'trading_status', 'trading_status_code', 'transaction_time', 'bid_count', ...]\n# Dtypes sample:\n# symbol                  object\n# ceiling                 int64\n# floor                   int64\n# ref_price               int64\n# stock_type              object\n# exchange                object\n# ...\n\n# Truy cập columns dễ dàng\nprint(board[['symbol', 'ref_price', 'match_price', 'total_volume']])\n```\n\n**Output với VCI:**\n```\n  symbol  ref_price  match_price  total_volume\n0    VCI      34850        34700      11768600\n1    VCB      84500        84600       2923100\n2    ACB      23450        23350      12219800\n```\n\n## 🎯 So Sánh Dữ Liệu Chi Tiết\n\n### price_board() Structure Comparison\n\n| Feature | KBS | VCI | Ưu Điểm |\n|---------|-----|-----|---------|\n| **Columns** | 28 | 77 | VCI cực kỳ chi tiết |\n| **Structure** | Flat columns | Flat columns | Cả hai đều dễ xử lý |\n| **Price Data** | OHLC, change | Full market depth | VCI đầy đủ hơn |\n| **Bid/Ask** | 3 levels | 3 levels | Cả hai đều có |\n| **Foreign Trading** | Buy/Sell volume | Buy/Sell value | VCI có thêm value |\n| **Processing** | Simple | Simple | Cả hai đều đơn giản |\n\n### Khi Nào Dùng Nguồn Nào?\n\n**Dùng KBS khi:**\n- Cần dữ liệu nhanh và ổn định\n- Chỉ cần thông tin cơ bản (giá, KL, thay đổi)\n- Xử lý data đơn giản với flat columns\n- Muốn data gọn gàng, dễ sử dụng\n\n**Dùng VCI khi:**\n- Cần phân tích sâu thị trường\n- Cần market detail đầy đủ (77 columns)\n- Cần foreign trading value\n- Muốn data chi tiết với flat columns (dễ xử lý)\n\n## 💡 Mẹo Sử Dụng\n\n### 1. Truy Cập Columns Dễ Dàng\n\n```python\n# Cả KBS và VCI đều có flat columns\ntrading_kbs = Trading(source=\"KBS\", symbol=\"VCI\")\ntrading_vci = Trading(source=\"VCI\", symbol=\"VCI\")\n\n# KBS - 28 columns\nboard_kbs = trading_kbs.price_board(symbols_list=['VCI', 'VCB'])\nprint(board_kbs[['symbol', 'reference_price', 'price_change']])\n\n# VCI - 77 columns\nboard_vci = trading_vci.price_board(symbols_list=['VCI', 'VCB'])\nprint(board_vci[['symbol', 'ref_price', 'match_price', 'total_volume']])\n\n# Cả hai đều dễ truy cập\nprint(f\"KBS columns: {len(board_kbs.columns)}\")\nprint(f\"VCI columns: {len(board_vci.columns)}\")\n```\n\n### 2. Lọc và Phân Tích Dữ Liệu\n\n```python\n# KBS - Lọc dữ liệu theo điều kiện\ntrading = Trading(source=\"KBS\", symbol=\"VCI\")\nboard = trading.price_board(symbols_list=['VCI', 'VCB', 'ACB', 'BID', 'CTG'])\n\n# Lọc các cổ phiếu tăng giá\nrisers = board[board['price_change'] > 0]\nprint(\"Cổ phiếu tăng giá:\")\nprint(risers[['symbol', 'reference_price', 'price_change', 'percent_change']])\n\n# Lọc theo khối lượng giao dịch\nhigh_volume = board[board['total_trades'] > 1000]\nprint(\"\\nCổ phiếu giao dịch sôi động:\")\nprint(high_volume[['symbol', 'total_trades', 'total_value']])\n\n# Tính toán thống kê\navg_change = board['percent_change'].mean()\ntotal_value = board['total_value'].sum()\nprint(f\"\\nTrung bình thay đổi: {avg_change:.2f}%\")\nprint(f\"Tổng giá trị giao dịch: {total_value:,.0f}\")\n```\n\n### 3. Real-time Monitoring\n\n```python\nimport time\nfrom vnstock import Trading\n\ndef monitor_price(symbols, interval=30):\n    \"\"\"Monitor price changes in real-time\"\"\"\n    trading = Trading(source=\"KBS\", symbol=symbols[0])\n    \n    while True:\n        try:\n            board = trading.price_board(symbols_list=symbols)\n            \n            # Hiển thị thông tin chính\n            for _, row in board.iterrows():\n                change_emoji = \"📈\" if row['price_change'] > 0 else \"📉\" if row['price_change'] < 0 else \"➡️\"\n                print(f\"{change_emoji} {row['symbol']}: {row['reference_price']} \"\n                      f\"({row['price_change']:+,} {row['percent_change']:+.2f}%)\")\n            \n            print(\"-\" * 50)\n            time.sleep(interval)\n            \n        except KeyboardInterrupt:\n            print(\"\\nStopped monitoring.\")\n            break\n        except Exception as e:\n            print(f\"Error: {e}\")\n            time.sleep(5)\n\n# Monitor VN30 stocks\nvn30_stocks = ['VCI', 'VCB', 'ACB', 'BID', 'CTG', 'HDB', 'MBB', 'SSB', 'STB', 'TCB', 'TPB', 'VIB']\nmonitor_price(vn30_stocks, interval=30)\n```\n\n### 4. Export và Analysis\n\n```python\n# Export data cho analysis\ntrading = Trading(source=\"KBS\", symbol=\"VCI\")\n\n# Lấy dữ liệu và export\nboard = trading.price_board(symbols_list=['VCI', 'VCB', 'ACB'])\nboard.to_csv('price_board.csv', index=False)\n\n# Analysis với pandas\nimport pandas as pd\n\n# Đọc lại data\ndf = pd.read_csv('price_board.csv')\n\n# Phân tích theo sàn\nexchange_stats = df.groupby('exchange').agg({\n    'total_value': 'sum',\n    'total_trades': 'sum',\n    'symbol': 'count'\n}).rename(columns={'symbol': 'stock_count'})\nprint(\"Thống kê theo sàn:\")\nprint(exchange_stats)\n\n# Phân tích theo mức thay đổi\ndf['change_category'] = pd.cut(df['percent_change'], \n                              bins=[-10, -2, 0, 2, 10], \n                              labels=['Giảm mạnh', 'Giảm nhẹ', 'Đứng giá', 'Tăng'])\nchange_dist = df['change_category'].value_counts()\nprint(\"\\nPhân bổ thay đổi giá:\")\nprint(change_dist)\n```\n\n## 🚨 Lưu Ý Quan Trọng\n\n1. **Rate Limits**: Cả hai nguồn đều có rate limits, tránh request quá nhanh\n2. **Market Hours**: Dữ liệu chỉ có trong giờ giao dịch (9:00-15:00)\n3. **Data Freshness**: KBS thường nhanh hơn VCI\n4. **Error Handling**: Luôn try-catch khi gọi API\n5. **Memory**: VCI data lớn hơn, cẩn thận với memory usage\n\n## 📚 Bước Tiếp Theo\n\n1. [02-Installation](02-installation.md) - Cài đặt\n2. [01-Overview](01-overview.md) - Tổng quan\n3. [03-Listing API](03-listing-api.md) - Danh sách mã\n4. [04-Company API](04-company-api.md) - Thông tin công ty\n5. ✅ **05-Trading API** - Bạn đã ở đây\n6. [06-Quote & Price](06-quote-price-api.md) - Giá lịch sử\n7. [07-Financial API](07-financial-api.md) - Dữ liệu tài chính\n\n---\n\n**Last Updated**: 2024-12-17  \n**Version**: 3.4.0  \n**Status**: Actively Maintained\n\nArchive v1.0.2: 28 files, 76988 bytes\n\nFiles: agents/openai.yaml (240b), references/capabilities.md (1125b), references/free_tier_playbook.md (891b), references/invocation_recipes.md (1285b), references/method_matrix.md (1190b), references/vnstock/01-overview.md (28095b), references/vnstock/02-installation.md (12228b), references/vnstock/03-listing-api.md (24904b), references/vnstock/04-company-api.md (21607b), references/vnstock/05-trading-api.md (9800b), references/vnstock/06-quote-price-api.md (13075b), references/vnstock/07-financial-api.md (25128b), references/vnstock/08-fund-api.md (5715b), references/vnstock/09-screener-api.md (215b), references/vnstock/10-connector-guide.md (11977b), references/vnstock/11-best-practices.md (14666b), references/vnstock/README.md (5901b), scripts/build_universe.py (3489b), scripts/catalog_vnstock.py (3439b), scripts/collect_fundamentals.py (3458b), scripts/collect_market_data.py (3471b), scripts/common.py (4475b), scripts/generate_report.py (2229b), scripts/invoke_vnstock.py (5084b), scripts/run_pipeline.py (2689b), scripts/score_stocks.py (2508b), SKILL.md (7047b), _meta.json (138b)\n\nFile v1.0.2:SKILL.md\n\n---\nname: vnstock-free-expert\ndescription: Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users request Vietnamese stock analysis under free-tier constraints.\ncompatibility: Requires Python 3.x, vnstock package, pandas, internet access, and optional VNSTOCK_API_KEY in .env.\n---\n\n# VNStock Free Expert\n\nUse this skill when the user needs advanced Vietnam stock analysis with `vnstock`, while staying safe on free-tier limits.\n\n## Important packaging note\nThis skill is self-contained and does not require shipping a separate `vnstock/` docs folder.\nAll operational knowledge needed by the agent is stored under:\n- `references/`\n\n## Read order\n1. Read `references/capabilities.md`.\n2. Read `references/method_matrix.md` for exact class/method mapping.\n3. Read `references/free_tier_playbook.md` before large runs.\n\n## Scope and constraints\n- Library: `vnstock` only.\n- Preferred sources: `kbs` first, `vci` fallback.\n- Never use `tcbs`.\n- Treat `Screener API` as unavailable unless user confirms it is restored in their installed version.\n\n## Free-tier operating rules\n- No API key: target <= 20 requests/minute.\n- Free API key: target <= 60 requests/minute.\n- Safe default pacing in scripts: 3.2s/request.\n- Reuse cached artifacts between steps.\n\n## Shared confidence rubric (required)\nReport confidence as `High` / `Medium` / `Low` using this standard:\n- `High`: universe coverage >= 95%, critical metrics coverage >= 80%, and hard errors <= 5% of symbols.\n- `Medium`: universe coverage >= 80%, critical metrics coverage >= 60%, and hard errors <= 15%.\n- `Low`: below `Medium` thresholds or material missing fields that can flip ranking results.\n\nAlways output:\n1. Confidence level.\n2. Coverage stats (`symbols_requested`, `symbols_scored`, `% missing by key metric`).\n3. Top missing fields that may change conclusions.\n\n## API key configuration (implemented)\n- Skill-local key file: `.env`\n- Variable: `VNSTOCK_API_KEY`\n- All API-calling scripts auto-load this key and call vnstock auth setup before requests.\n- You can override per run with `--api-key \"...\"`.\n\n## Execution workflow (ordered)\n1. Validate environment (`python`, `vnstock`, `pandas`) and load optional API key from `.env`.\n2. Build a universe using `scripts/build_universe.py` (`group`, `exchange`, or `symbols` mode).\n3. Collect market data with `scripts/collect_market_data.py` using safe pacing.\n4. Collect fundamentals with `scripts/collect_fundamentals.py`.\n5. Score and rank using `scripts/score_stocks.py`.\n6. Generate analyst-style memo with `scripts/generate_report.py`.\n7. Apply confidence rubric, disclose missing fields, and summarize risks.\n\n## Downstream handoff bundle (required when doing single-ticker deep dive)\nWhen the user request is about valuing or building a memo for a **specific ticker** (or a small list), output a compact JSON bundle that downstream skills can reuse:\n- `ticker`, `as_of_date`, `currency`\n- `financials` (income/balance/cashflow + key ratios if available)\n- `price_history` (returns 1m/3m/6m/12m)\n- `peer_set` (if you built one)\n- `metadata.source` and `data_quality_notes`\n\nThis bundle is designed to feed `equity-valuation-framework` and `portfolio-risk-manager`.\n\n## Script map\n\n### A) Discovery and universal invocation (for broad feature coverage)\n\n1. `catalog_vnstock.py`\nPath: `scripts/catalog_vnstock.py`\n\nUse when:\n- You need to inspect available classes/methods in the installed `vnstock` version.\n- You want to confirm compatibility before running a method.\n\n2. `invoke_vnstock.py`\nPath: `scripts/invoke_vnstock.py`\n\nUse when:\n- You need to call any supported class/method beyond the prebuilt valuation pipeline.\n- You want one generic entry point for `Listing`, `Quote`, `Company`, `Finance`, `Trading`, `Fund`, or other exported classes.\n\nThis script supports dynamic invocation by class name and method name with JSON kwargs.\n\n### B) Valuation pipeline scripts\n\n1. `build_universe.py`\nUse when building symbol universe from index/exchange/custom symbol list.\nInput: source + mode + group/exchange/symbols.\nOutput: `outputs/universe_*.csv` and latest pointers.\n\n2. `collect_market_data.py`\nUse when collecting OHLCV/momentum fields (3M, 6M, 12M returns).\nInput: universe CSV path.\nOutput: `outputs/market_data_*.csv` + per-symbol errors in JSON.\n\n3. `collect_fundamentals.py`\nUse when collecting valuation and quality metrics from finance/company APIs.\nInput: universe CSV path.\nOutput: `outputs/fundamentals_*.csv` + per-symbol errors in JSON.\n\n4. `score_stocks.py`\nUse when ranking symbols with composite scoring.\nInput: market + fundamentals CSV files.\nOutput: `outputs/ranking_*.csv`.\n\n5. `generate_report.py`\nUse when converting ranking output to analyst-style markdown memo.\nInput: ranking CSV file.\nOutput: `outputs/investment_memo_*.md`.\n\n6. `run_pipeline.py`\nUse when running the end-to-end pipeline in one command.\nInput: source + universe mode.\nOutput: all artifacts above in one run.\n\n## Error handling rules\n1. Log symbol-level failures and continue processing remaining symbols.\n2. Do not claim missing metrics as zeros; mark them as missing.\n3. If a critical step fails, stop and report failed step + command + suggested retry scope.\n\n## Recommended decision logic\n1. If request is “standard valuation/ranking”: run pipeline scripts.\n2. If request needs a specific vnstock capability not in pipeline: use `catalog_vnstock.py` then `invoke_vnstock.py`.\n3. If request volume is large: apply `free_tier_playbook.md` throttling and chunking strategy.\n\n## Confidence aggregation (required)\nWhen output includes ranking and valuation interpretation:\n1. Compute data confidence from coverage metrics (`symbols_scored`, missing key fields, error ratio).\n2. Compute model confidence from method robustness (single metric vs multi-factor consistency).\n3. Final confidence = lower of data confidence and model confidence.\n4. In `Low` confidence cases, provide directional output only and list required missing inputs.\n\n## Required output template\n1. `What Was Run`: scripts, source, universe scope, and pacing profile.\n2. `Coverage`: requested symbols, scored symbols, and missingness by key field.\n3. `Top Results`: ranked list with score columns.\n4. `Key Risks`: concentration, stale data, missing metrics, or provider limitations.\n5. `Confidence and Gaps`: final confidence + exact blockers.\n\n## Quick command examples\n```bash\npython scripts/catalog_vnstock.py --outdir ./outputs\npython scripts/invoke_vnstock.py --class-name Quote --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"VCB\"}' --method history --method-kwargs '{\"start\":\"2024-01-01\",\"end\":\"2024-12-31\",\"interval\":\"1D\"}' --outdir ./outputs\npython scripts/run_pipeline.py --source kbs --mode group --group VN30 --outdir ./outputs\n```\n\n## Trigger examples\n- \"Analyze VN30 using vnstock but keep it free-tier safe.\"\n- \"Rank Vietnamese stocks by value/quality/momentum with KBS data.\"\n- \"Run a full vnstock pipeline and return top candidates with risk notes.\"\n\nFile v1.0.2:references/vnstock/README.md\n\n# VNStock 3.4.0 - Tài Liệu Hướng Dẫn\n\n## 🎯 Giới Thiệu\n\n**VNStock** là thư viện Python để lấy dữ liệu chứng khoán Việt Nam từ nhiều nguồn uy tín. Thiết kế với kiến trúc provider-based, cho phép chuyển đổi linh hoạt giữa các nguồn dữ liệu khác nhau.\n\n### ✨ Tính Năng Chính\n\n- ✅ **Nhiều nguồn dữ liệu**: VCI, KBS, MSN (API công khai); FMP, DNSE (API chính thức)\n- ⚠️ **TCBS**: Ngưng cập nhật thêm từ v3.4.0, sẽ loại bỏ trong v3.5.0 (tháng 3/2026)\n- ✅ **API thống nhất**: Cùng interface cho tất cả nguồn\n- ✅ **Dữ liệu lịch sử & Real-time**: Giá, công ty, tài chính\n- ✅ **Dữ liệu công ty**: Hồ sơ, cổ đông, nhân viên quản lý\n- ✅ **Dữ liệu tài chính**: Báo cáo, chỉ số, lưu chuyển tiền tệ\n- ✅ **Lọc & Phân loại**: Theo ngành, sàn giao dịch, chỉ số\n\n## 📚 Hướng Dẫn Sử Dụng\n\n| Tài Liệu | Nội Dung | Mức Độ |\n|---------|---------|--------|\n| **[01-Overview](01-overview.md)** | Tổng quan kiến trúc, các loại dữ liệu | Cơ bản |\n| **[02-Installation](02-installation.md)** | Cài đặt, thiết lập, kiểm tra | Cơ bản |\n| **[03-Listing API](03-listing-api.md)** | API tìm kiếm và lọc chứng khoán | Cơ bản |\n| **[04-Company API](04-company-api.md)** | Thông tin công ty, cổ đông, nhân viên quản lý | Cơ bản |\n| **[05-Trading API](05-trading-api.md)** | Dữ liệu giao dịch, bid/ask, thống kê | Cơ bản |\n| **[06-Quote & Price](06-quote-price-api.md)** | API lấy giá lịch sử và real-time | Cơ bản |\n| **[07-Financial API](07-financial-api.md)** | API dữ liệu tài chính và báo cáo | Trung cấp |\n| **[08-Fund API](08-fund-api.md)** | Dữ liệu quỹ đầu tư mở (Fmarket) | Trung cấp |\n| **[09-Screener API](09-screener-api.md)** | Công cụ lọc chứng khoán nâng cao | Nâng cao |\n| **[10-Connector Guide](10-connector-guide.md)** | Hướng dẫn API bên ngoài (FMP, XNO, DNSE) | Nâng cao |\n| **[11-Best Practices](11-best-practices.md)** | Mẹo tối ưu hóa, xử lý lỗi, security | Nâng cao |\n\n## 🚀 Bắt Đầu Nhanh\n\n### Cài Đặt\n\n```bash\npip install vnstock\n```\n\nXem chi tiết tại **[02-Installation](02-installation.md)**\n\n## 📖 Cấu Trúc Tài Liệu\n\nTài liệu được chia thành 11 phần theo thứ tự từ cơ bản đến nâng cao:\n\n1. **[01-Overview](01-overview.md)** - Hiểu kiến trúc và các loại dữ liệu\n2. **[02-Installation](02-installation.md)** - Cài đặt và kiểm tra môi trường\n3. **[03-Listing API](03-listing-api.md)** - Tìm kiếm danh sách chứng khoán\n4. **[04-Company API](04-company-api.md)** - Lấy thông tin công ty chi tiết\n5. **[05-Trading API](05-trading-api.md)** - Dữ liệu giao dịch thị trường\n6. **[06-Quote & Price](06-quote-price-api.md)** - Lấy dữ liệu giá\n7. **[07-Financial API](07-financial-api.md)** - Truy cập dữ liệu tài chính\n8. **[08-Fund API](08-fund-api.md)** - Thông tin quỹ đầu tư mở\n9. **[09-Screener API](09-screener-api.md)** - Lọc chứng khoán nâng cao\n10. **[10-Connector Guide](10-connector-guide.md)** - Sử dụng API bên ngoài\n11. **[11-Best Practices](11-best-practices.md)** - Tối ưu hóa và xử lý lỗi\n\n## Kiến Trúc Hệ Thống\n\nVNStock sử dụng kiến trúc provider-based cho phép chuyển đổi linh hoạt giữa các nguồn dữ liệu:\n\n```\nỨng Dụng\n   ↓\nAPI Thống Nhất (Quote, Listing, Finance, Company)\n   ↓\nAdapter Layer (Chuẩn hóa dữ liệu)\n   ↓\nCác Nguồn Dữ Liệu (Web Scraping & API bên ngoài)\n```\n\n## 📊 Nguồn Dữ Liệu\n\n### Web Scraping\n\n| Nguồn | Danh Sách | Giá | Công Ty | Tài Chính | Trạng Thái |\n|-------|----------|-----|--------|----------|-----------|\n| **VCI** | ✅ | ✅ | ✅ | ✅ | Hoạt động |\n| **KBS** | ✅ | ✅ | ✅ | ✅ | Mới (v3.4.0) |\n| **MSN** | ✅ | ✅ | ❌ | ❌ | Hoạt động |\n\n### API Bên Ngoài\n\n| API | Giá | Tài Chính | Công Ty |\n|-----|-----|----------|---------|\n| **FMP** | ✅ | ✅ | ✅ |\n| **XNO** | ✅ | ✅ | ✅ |\n| **DNSE** | ✅ | ❌ | ❌ |\n\n## 🎓 Lộ Trình Học Tập\n\nKhuyến nghị làm theo thứ tự từ trên xuống để hiểu toàn bộ hệ thống:\n\n1. **[01-Overview](01-overview.md)** - Nắm vững kiến trúc và các khái niệm cơ bản\n2. **[02-Installation](02-installation.md)** - Cài đặt và xác nhận môi trường hoạt động\n3. **[03-Listing API](03-listing-api.md)** - Tìm kiếm chứng khoán theo tiêu chí\n4. **[03a-Company API](03a-company-api.md)** - Tìm hiểu chi tiết về công ty\n5. **[03b-Trading API](03b-trading-api.md)** - Phân tích dữ liệu giao dịch\n6. **[04-Quote & Price](04-quote-price-api.md)** - Truy cập dữ liệu giá chứng khoán\n7. **[05-Financial API](05-financial-api.md)** - Lấy dữ liệu tài chính chi tiết\n8. **[05a-Fund API](05a-fund-api.md)** - Khám phá quỹ đầu tư mở\n9. **[06-Connector Guide](06-connector-guide.md)** - Sử dụng API bên ngoài (FMP, XNO, DNSE)\n10. **[06a-Screener API](06a-screener-api.md)** - Lọc chứng khoán theo tiêu chí nâng cao\n11. **[07-Best Practices](07-best-practices.md)** - Áp dụng tối ưu hóa, xử lý lỗi, security\n\n## 🔗 Liên Kết Hữu Ích\n\n- **[GitHub](https://github.com/thinh-vu/vnstock)** - Mã nguồn và issue tracking\n- **[PyPI](https://pypi.org/project/vnstock)** - Cài đặt package\n- **[Website](https://vnstocks.com)** - Trang chính thức\n\n## ℹ️ Thông Tin Phiên Bản\n\n- **Phiên bản**: 3.4.0\n- **Cập nhật lần cuối**: 2024-12-17\n- **Trạng thái**: Đang bảo trì ✅\n- **Thông báo**: TCBS đã ngưng được cập nhật, sẽ loại bỏ trong v3.5.0 (tháng 3/2026)\n- **License**: MIT\n\nFile v1.0.2:_meta.json\n\n{\n  \"ownerId\": \"kn7aqz9b9xv2mmyvsg54n5kecn81kkaf\",\n  \"slug\": \"vnstock-free-expert\",\n  \"version\": \"1.0.2\",\n  \"publishedAt\": 1771982403105\n}\n\nFile v1.0.2:references/capabilities.md\n\n# VNStock Capability Reference (Self-Contained)\n\n## Core capabilities\n- Symbol universe and classification: exchanges, industries, index groups, derivatives/bonds/warrants listings.\n- Company intelligence: overview, shareholders, officers, subsidiaries, affiliates, events, reports (source-dependent).\n- Market data: historical OHLCV, intraday prints, board snapshots, market depth (source-dependent).\n- Financial statements and ratios: income statement, balance sheet, cash flow, ratio with period modes.\n- Fund data: investment fund listings and related metadata.\n- External connectors: available depending on environment and API keys.\n\n## Source strategy\n- Primary source: `kbs`.\n- Secondary fallback: `vci`.\n- Do not use `tcbs`.\n\n## Data caveats\n- Method availability differs by source.\n- Some methods may return empty frames for specific symbols/time windows.\n- Realtime/near-realtime outputs depend on market hours and provider freshness.\n\n## Safe analysis pattern\n1. Fetch raw data.\n2. Validate shape/columns.\n3. Handle empty/missing values.\n4. Compute derived metrics.\n5. Separate factual output from interpretation.\n\nFile v1.0.2:references/free_tier_playbook.md\n\n# Free-Tier Playbook\n\n## Rate limit profile\n- Guest/no key: 20 requests/minute.\n- Free key: up to 60 requests/minute.\n\n## Execution controls\n- Default minimum interval: 3.2 seconds/request.\n- For unstable network/provider: increase to 4-5 seconds/request.\n- Process symbols in chunks (e.g. 20-50 symbols/batch).\n\n## Resilience checklist\n- Retry transient failures with backoff.\n- Log per-symbol failures; do not fail the whole run if a single symbol fails.\n- Save intermediate artifacts (`universe`, `market_data`, `fundamentals`) for resume.\n\n## Data quality checklist\n- Confirm expected columns exist before calculation.\n- Track missing metrics ratio.\n- Flag stale data windows and low-bar histories.\n\n## Portfolio-analysis checklist\n- Use relative ranking, not absolute threshold only.\n- Validate top picks against recent macro/news context.\n- Apply sector diversification and risk caps.\n\nFile v1.0.2:references/invocation_recipes.md\n\n# Invocation Recipes\n\n## 1) Quote history\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Quote \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"VCB\"}' \\\n  --method history \\\n  --method-kwargs '{\"start\":\"2024-01-01\",\"end\":\"2024-12-31\",\"interval\":\"1D\"}' \\\n  --outdir ./outputs\n```\n\n## 2) Company overview\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Company \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"FPT\"}' \\\n  --method overview \\\n  --method-kwargs '{}' \\\n  --outdir ./outputs\n```\n\n## 3) Finance ratio (year)\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Finance \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"ACB\"}' \\\n  --method ratio \\\n  --method-kwargs '{\"period\":\"year\"}' \\\n  --outdir ./outputs\n```\n\n## 4) Listing by group\n```bash\npython /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Listing \\\n  --init-kwargs '{\"source\":\"kbs\"}' \\\n  --method symbols_by_group \\\n  --method-kwargs '{\"group\":\"VN30\"}' \\\n  --outdir ./outputs\n```\n\nFile v1.0.2:references/method_matrix.md\n\n# VNStock Method Matrix\n\nThis matrix lists common class-method combinations used in practice. Use `catalog_vnstock.py` to verify exact availability in the local installed version.\n\n## Listing\n- `all_symbols()`\n- `symbols_by_exchange()`\n- `symbols_by_industries()`\n- `industries_icb()`\n- `symbols_by_group()`\n- `all_indices()`\n- `indices_by_group()`\n- `all_future_indices()`\n- `all_government_bonds()`\n- `all_covered_warrant()`\n- `all_bonds()`\n\n## Quote\n- `history(...)`\n- `intraday(...)`\n- `price_depth(...)` (source-dependent)\n\n## Company\n- `overview()`\n- `shareholders()`\n- `officers()`\n- `subsidiaries()`\n- `affiliate()`\n- `news()`\n- `events()`\n- `ownership()` (source-dependent)\n- `capital_history()` (source-dependent)\n- `insider_trading()` (source-dependent)\n- `reports()` (source-dependent)\n- `trading_stats()` (source-dependent)\n- `ratio_summary()` (source-dependent)\n\n## Finance\n- `income_statement(period=...)`\n- `balance_sheet(period=...)`\n- `cash_flow(period=...)`\n- `ratio(period=...)`\n\n## Trading\n- `price_board(symbols_list=...)`\n\n## Fund\n- `listing(...)`\n\n## Universal method access\nUse `invoke_vnstock.py` for any class/method not explicitly hardcoded in pipeline scripts.\n\nFile v1.0.2:references/vnstock/01-overview.md\n\n# Vnstock 3.4.0 - Tổng Quan Kiến Trúc & Dữ Liệu\n\n**Phiên bản:** 3.4.0+  \n\n**Cập nhật:** Tháng 1, 2026  \n\n**Trạng thái:** Hoạt động\n\n---\n\n## 📚 Mục Lục\n\n1. [Giới Thiệu](#giới-thiệu)\n2. [Các Plan & Rate Limit](#các-plan--rate-limit)\n3. [Kiến Trúc Tổng Thể](#kiến-trúc-tổng-thể)\n4. [Phân Tầng Dữ Liệu (Data Layers)](#phân-tầng-dữ-liệu-data-layers)\n5. [Các APIs & Dữ Liệu Hiện Có](#các-apis--dữ-liệu-hiện-có)\n6. [Nguồn Dữ Liệu & Connectors](#nguồn-dữ-liệu--connectors)\n7. [Core Utilities](#core-utilities)\n8. [Cách Sử Dụng Cơ Bản](#cách-sử-dụng-cơ-bản)\n\n---\n\n## 📖 Giới Thiệu\n\n**Vnstock** là thư viện Python mạnh mẽ để lấy dữ liệu chứng khoán Việt Nam từ nhiều nguồn uy tín. Thư viện được thiết kế với kiến trúc provider-based, cho phép dễ dàng chuyển đổi giữa các nguồn dữ liệu khác nhau mà không thay đổi code.\n\n### 🎯 Đặc Điểm Chính\n\n- **Nhiều nguồn dữ liệu**: VCI, KBS, MSN, và các connectors bên ngoài (FMP, DNSE)\n- **API thống nhất**: Cùng một interface cho tất cả các nguồn dữ liệu\n- **Dữ liệu lịch sử & Real-time**: Giá lịch sử, dữ liệu trong ngày, giá realtime\n- **Dữ liệu công ty**: Hồ sơ công ty, cổ đông chính, nhân viên quản lý\n- **Dữ liệu tài chính**: Báo cáo tài chính, chỉ số tài chính, các dòng tiền\n- **Lọc & Phân loại**: Tìm kiếm theo ngành, sàn giao dịch, chỉ số\n- **Xử lý lỗi thông minh**: Retry tự động với exponential backoff\n\n⚠️ **TCBS**: Đã ngưng cập nhật từ v3.4.0, sẽ loại bỏ trong v3.5.0 (tháng 3/2026)\n\n---\n\n## 💳 So sánh các gói sử dụng & giới hạn\n\nVnstock cung cấp các gói sử dụng khác nhau phù hợp với từng nhu cầu cụ thể, xem thông tin chính xác được chia sẻ tại website Vnstock [Gói tài trợ Vnstock](https://vnstocks.com/insiders-program):\n\n### So sánh gói sử dụng\n\n| Tiêu Chí          | Khách | Cộng đồng (Tiêu chuẩn)  | Bronze    | Silver    | Golden    |\n| ----------------- | ----- | ----- | --------- | --------- | --------- |\n| **Giới Hạn/Phút** | 20    | 60    | 180 (3x)  | 300 (5x) | 500 (10x) |\n| **Giới Hạn/Giờ**  | 1.2K  | 3.6K  | 10.8K     | 18K       | 36K       |\n| **Giới Hạn/Ngày** | 5K    | 10K   | 50K       | 100K      | 150K      |\n| **Đăng Nhập**     | ❌    | ✅    | ✅        | ✅        | ✅        |\n| **API Key**       | ❌    | ✅    | ✅        | ✅        | ✅        |\n| **vnstock_data**  | ❌    | ❌    | ✅        | ✅        | ✅        |\n| **Hỗ Trợ**        | ❌    | ❌    | ✅        | ✅        | ✅        |\n| **Cam Kết**       | Không | Không | Linh Hoạt | Quý       | 1 Năm     |\n\n(*) **Lưu ý quan trọng về Rate Limit:**\n- Khi chạm giới hạn API, chương trình sẽ tự động dừng để bảo vệ hệ thống\n- Số lượng request trên mang tính tham khảo và có thể thay đổi\n- Giới hạn thực tế phụ thuộc vào: giới hạn của Vnstock và giới hạn của server nguồn dữ liệu\n- Khuyến nghị: Sử dụng cache dữ liệu để tối ưu hiệu suất\n\n### 🎯 Chọn Plan Nào?\n\n#### 1. **Guest** - Trải Nghiệm Nhanh\n\n- **Ai nên dùng**: Người mới, thử nghiệm, không cam kết\n- **Đặc điểm**: \n    - Không cần đăng nhập hay API key\n    - Giới hạn 20 request/phút (1.2K/giờ, 5K/ngày)\n    - Thích hợp cho khám phá nhanh\n- **Ví dụ**: `quote = Quote(source=\"vci\", symbol=\"VCB\")`\n\n#### 2. **Free** - Học Tập & Phát Triển\n\n- **Ai nên dùng**: Sinh viên, developer mới, người học Python\n- **Đặc điểm**:\n    - Cần đăng nhập tài khoản vnstock & API key\n    - Giới hạn 60 request/phút (3.6K/giờ, 10K/ngày) - **3x Guest**\n    - Đủ cho phát triển & kiểm thử cơ bản\n- **Cách bắt đầu**: Đăng ký miễn phí tại https://vnstocks.com/login\n- **Ví dụ**: \n\n  ```python\n  from vnstock import config\n  config.set_api_key(\"your_api_key\")\n  quote = Quote(source=\"vci\", symbol=\"VCB\")\n  ```\n\n#### 3. **Bronze** - Dữ Liệu Cơ Bản\n\n- **Ai nên dùng**: Nhà phân tích, trader cá nhân, startup\n- **Đặc điểm**:\n    - Giới hạn 180 request/phút (10.8K/giờ, 50K/ngày) - **9x Guest**\n    - Truy cập **vnstock_data** với dữ liệu nâng cao\n    - Plan linh hoạt (hàng tháng hoặc quý)\n    - Hỗ trợ cơ bản\n- **Tính năng nâng cao**: Xem [vnstock_data Overview](../vnstock-data/01-overview.md)\n- **Tham gia**: https://vnstocks.com/insiders-program\n\n#### 4. **Silver** - Chức Năng Mở Rộng\n\n- **Ai nên dùng**: nhóm, quản lý quỹ đầu tư, dự án công khai\n- **Đặc điểm**:\n    - Giới hạn 300 request/phút (18K/giờ, 100K/ngày) - **15x Guest**\n    - Truy cập hầu hết chức năng nâng cao của vnstock_data\n    - Plan quý (3 tháng)\n    - Hỗ trợ ưu tiên\n- **Tính năng nâng cao**: Xem [vnstock_data Overview](../vnstock-data/01-overview.md)\n- **Tham gia**: https://vnstocks.com/insiders-program\n\n#### 5. **Golden** - Toàn Bộ Chức Năng\n\n- **Ai nên dùng**: Dự án lâu dài, đồng hành bền vững cùng dự án\n- **Đặc điểm**:\n    - Giới hạn 600 request/phút (36K/giờ, 150K/ngày) - **30x Guest**\n    - Truy cập **tất cả** chức năng của bộ thư viện tài trợ\n    - Plan 1 năm (cam kết lâu dài)\n    - Hỗ trợ tối ưu & ưu đãi chi phí tốt nhất\n- **Tính năng nâng cao**: Xem [vnstock_data Overview](../vnstock-data/01-overview.md)\n- **Tham gia**: https://vnstocks.com/insiders-program\n\n### 📊 Rate Limit Chi Tiết\n\n```python\nTIER_LIMITS = {\n    \"guest\": {\"min\": 20, \"hour\": 1200, \"day\": 5000},\n    \"free\": {\"min\": 60, \"hour\": 3600, \"day\": 10000},\n    \"bronze\": {\"min\": 180, \"hour\": 10800, \"day\": 50000},\n    \"silver\": {\"min\": 300, \"hour\": 15000, \"day\": 100000},\n    \"golden\": {\"min\": 500, \"hour\": 30000, \"day\": 150000}\n}\n```\n\n### 🚀 Nâng Cấp\n\nKhi bạn gặp rate limit:\n\n```python\nfrom vnstock.core.quota import RateLimitExceeded\n\ntry:\n    quote = Quote(source=\"vci\", symbol=\"VCB\")\n    df = quote.history(start=\"2024-01-01\", end=\"2024-12-31\")\nexcept RateLimitExceeded as e:\n    print(e)  # Sẽ hiển thị hướng dẫn nâng cấp phù hợp\n```\n\n---\n\n## 🏗️ Kiến Trúc Tổng Thể\n\nVnstock được thiết kế theo **Adapter Pattern** với các tầng rõ ràng:\n\n```\n┌─────────────────────────────────────────┐\n│         User Code (Your App)            │\n├─────────────────────────────────────────┤\n│  Quote | Listing | Company | Finance    │  ← Unified API Layer\n│  Trading | Misc (Gold, FX)              │\n├─────────────────────────────────────────┤\n│  Provider Registry (Dynamic Discovery)  │\n├─────────────────────────────────────────┤\n│        Explorer (Web Scraping)          │\n│  ┌──────────────────────────────────┐   │\n│  │ VCI | KBS | MSN | FMarket        │   │\n│  └──────────────────────────────────┘   │\n│                                          │\n│    Connector (Official APIs)             │\n│  ┌──────────────────────────────────┐   │\n│  │ FMP | DNSE | Binance             │   │\n│  └──────────────────────────────────┘   │\n└─────────────────────────────────────────┘\n```\n\n### Cấu Trúc Thư Mục Hiện Tại\n\n```\nvnstock/\n├── api/                          # Unified API Layer (Facade)\n│   ├── __init__.py\n│   ├── quote.py                  # Quote API\n│   ├── company.py                # Company API\n│   ├── financial.py              # Finance API\n│   ├── trading.py                # Trading API\n│   ├── listing.py                # Listing API\n│   └── ...\n│\n├── explorer/                     # Data Explorers (Source-specific)\n│   ├── kbs/                      # KB Securities\n│   │   ├── quote.py\n│   │   ├── company.py\n│   │   ├── financial.py\n│   │   ├── trading.py\n│   │   ├── listing.py\n│   │   └── const.py\n│   │\n│   ├── vci/                      # VCI\n│   │   ├── quote.py\n│   │   ├── company.py\n│   │   ├── financial.py\n│   │   ├── trading.py\n│   │   ├── listing.py\n│   │   └── const.py\n│   │\n│   ├── misc/                     # Miscellaneous (Utilities)\n│   │   ├── gold_price.py         # Giá vàng\n│   │   └── exchange_rate.py      # Tỷ giá ngoại tệ\n│   │\n│   └── ... (MAS, VND, CafeF, FMarket, MBK, SPL, MSN, TCBS, v.v.)\n│\n├── connector/                    # Low-level Connectors\n│   ├── dnse/                     # DNSE Trading\n│   ├── fmp/                      # FMP (Financial Modeling Prep)\n│   ├── binance/                  # Binance (Crypto - sắp tới)\n│   └── ...\n│\n├── core/                         # Core Utilities & Infrastructure\n│   ├── utils/\n│   │   ├── market.py             # Giờ giao dịch, trạng thái thị trường\n│   │   ├── interval.py           # Xử lý timeframe (1D, 1H, 1m, v.v.)\n│   │   ├── lookback.py           # Xử lý lookback period (1M, 3M, 100D, v.v.)\n│   │   ├── transform.py          # Chuyển đổi dữ liệu (long/wide format)\n│   │   ├── parser.py             # Parse dữ liệu từ các nguồn\n│   │   ├── validation.py         # Kiểm tra dữ liệu\n│   │   ├── auth.py               # Xác thực API key\n│   │   ├── client.py             # HTTP client\n│   │   ├── proxy_manager.py      # Quản lý proxy\n│   │   ├── logger.py             # Logging\n│   │   └── ... (19+ utilities)\n│   │\n│   ├── types.py                  # Type definitions\n│   ├── models.py                 # Data models\n│   ├── registry.py               # Provider registry\n│   └── ...\n│\n├── base.py                       # Base classes (BaseAdapter, etc.)\n├── config.py                     # Configuration\n├── constants.py                  # Constants\n└── __init__.py                   # Package initialization\n```\n\n### Cách Hoạt Động\n\n1. **Adapter Layer**: Bạn sử dụng các class như `Quote`, `Listing`, `Company` v.v.\n2. **Provider Registry**: Thư viện tìm kiếm provider phù hợp dựa trên `source` parameter\n3. **Dynamic Method Detection**: Chỉ các phương thức mà provider hỗ trợ mới được gọi\n4. **Parameter Filtering**: Tự động lọc tham số để phù hợp với provider signature\n\n---\n\n## 📊 Phân Tầng Dữ Liệu (Data Layers)\n\nVnstock tổ chức dữ liệu thành các tầng theo mô hình tham khảo từ các nguồn quốc tế như Bloomberg Terminal, FinancialModelingPrep, vv\n\n### Tầng 1: Reference Data (Dữ Liệu Tham Chiếu)\n\n**Mục đích:** Master data, identifiers, classifications\n\n**Dữ Liệu Hiện Có:**\n\n- **Listing API**: Danh sách chứng khoán, chỉ số, sàn giao dịch\n- **Company API**: Thông tin công ty, cổ đông, ban lãnh đạo\n\n**Methods:**\n\n```python\nfrom vnstock import Listing, Company\n\n# Listing - Danh sách chứng khoán\nlisting = Listing(source=\"vci\")\nsymbols = listing.all_symbols()           # Tất cả mã chứng khoán\nindices = listing.indices()               # Danh sách chỉ số\nbonds = listing.government_bonds()        # Trái phiếu (VCI only)\n\n# Company - Thông tin công ty\ncompany = Company(source=\"vci\", symbol=\"VCB\")\nprofile = company.overview()              # Thông tin tổng quan\nshareholders = company.shareholders()     # Cổ đông lớn\nofficers = company.officers()             # Ban lãnh đạo\nsubsidiaries = company.subsidiaries()     # Công ty con\ncapital_history = company.capital_history()  # Lịch sử vốn (KBS only)\n```\n\n---\n\n### Tầng 2: Market Data (Dữ Liệu Thị Trường)\n\n**Mục đích:** Giá, khối lượng, sổ lệnh, dữ liệu tick\n\n**Dữ Liệu Hiện Có:**\n\n- **Quote API**: Giá lịch sử, intraday, sổ lệnh\n- **Trading API**: Bảng giá, thống kê giao dịch\n\n**Methods:**\n\n```python\nfrom vnstock import Quote, Trading\n\n# Quote - Dữ liệu giá\nquote = Quote(source=\"vci\", symbol=\"VCB\")\nhistory = quote.history(\n    start=\"2024-01-01\",\n    end=\"2024-12-31\",\n    interval=\"1D\"  # 1D, 1H, 1m, 5m, 15m, 30m\n)\nintraday = quote.intraday()               # Dữ liệu trong ngày\ndepth = quote.price_depth()               # Sổ lệnh\n\n# Trading - Dữ liệu giao dịch\ntrading = Trading(source=\"vci\")\nboard = trading.price_board([\"VCB\", \"VNM\"])  # Bảng giá\nprice_history = trading.price_history()      # Lịch sử giá (VCI only)\ntrading_stats = trading.trading_stats()      # Thống kê giao dịch (VCI only)\n```\n\n**Hỗ trợ TimeFrame:**\n\n- Intraday: `1m`, `5m`, `15m`, `30m`, `1H`, `4h`\n- Daily+: `1D`, `1W`, `1M`\n\n---\n\n### Tầng 3: Fundamental Data (Dữ Liệu Cơ Bản)\n\n**Mục đích:** Báo cáo tài chính, chỉ số, tỷ lệ\n\n**Dữ Liệu Hiện Có:**\n\n- **Finance API**: Báo cáo tài chính (Income, Balance Sheet, Cash Flow, Ratios)\n\n**Methods:**\n\n```python\nfrom vnstock import Finance\n\nfinance = Finance(source=\"vci\", symbol=\"VCB\")\n\n# Báo cáo tài chính\nincome = finance.income_statement(period=\"year\")      # Báo cáo thu nhập\nbalance = finance.balance_sheet(period=\"quarter\")     # Bảng cân đối\ncashflow = finance.cash_flow(period=\"year\")           # Dòng tiền\nratios = finance.ratio(period=\"year\")                 # Chỉ số tài chính\n```\n\n**Hỗ trợ Periods:**\n\n- `year` - Hàng năm\n- `quarter` - Hàng quý\n\n---\n\n### Tầng 4: Alternative Data (Dữ Liệu Thay Thế)\n\n**Mục đích:** Tin tức, sự kiện, dữ liệu tiện ích\n\n**Dữ Liệu Hiện Có:**\n\n- **Company.news()**: Tin tức công ty\n- **Misc utilities**: Giá vàng, tỷ giá ngoại tệ\n\n**Methods:**\n\n```python\nfrom vnstock import Company\nfrom vnstock.explorer.misc import GoldPrice, ExchangeRate\n\n# Tin tức\ncompany = Company(source=\"vci\", symbol=\"VCB\")\nnews = company.news()\n\n# Giá vàng\ngold = GoldPrice()\ngold_price = gold.get_latest()\n\n# Tỷ giá ngoại tệ\nfx = ExchangeRate()\nusd_vnd = fx.get_rate(\"USD\", \"VND\")\n```\n\n---\n\n### Tầng 5-7: Analytics, Macro, Insights\n\n**Trạng thái:** Chưa triển khai đầy đủ\n\n- **Layer 5 (Analytics)**: Chỉ số kỹ thuật, mô hình định giá, vv (chưa đầy đủ) - có thư viện vnstock_ta cung cấp tính toán bộ chỉ báo kỹ thuật.​\n- **Layer 6 (Macro)**: Chỉ số kinh tế, hàng hóa - chỉ có trong thư viện vnstock_data yêu cầu tham gia gói tài trợ Vnstock.\n- **Layer 7 (Insights)**: Screener, rankings top stocks, vv - (Chưa đầy đủ) - chỉ có trong thư viện vnstock_data yêu cầu tham gia gói tài trợ Vnstock.\n\n---\n\n## 📋 Các APIs & Dữ Liệu Hiện Có\n\n### 1. Quote API - Dữ Liệu Giá\n\n| Method          | Mô Tả                        | Sources            |\n| --------------- | ---------------------------- | ------------------ |\n| `history()`     | Dữ liệu lịch sử OHLCV        | KBS, VCI, MSN, FMP |\n| `intraday()`    | Dữ liệu giao dịch trong ngày | KBS, VCI           |\n| `price_depth()` | Sổ lệnh (order book)         | KBS, VCI           |\n\n**Ứng Dụng:** Phân tích kỹ thuật, backtest chiến lược, tính toán chỉ số\n\n---\n\n### 2. Company API - Thông Tin Công Ty\n\n| Method              | Mô Tả               | Sources             |\n| ------------------- | ------------------- | ------------------- |\n| `overview()`        | Thông tin tổng quan | KBS, VCI, TCBS, FMP |\n| `officers()`        | Ban lãnh đạo        | KBS, VCI, TCBS      |\n| `shareholders()`    | Cổ đông lớn         | KBS, VCI, TCBS      |\n| `subsidiaries()`    | Công ty con         | KBS, VCI, TCBS      |\n| `news()`            | Tin tức             | KBS, VCI, TCBS      |\n| `capital_history()` | Lịch sử vốn         | KBS only            |\n| `ratio_summary()`   | Tóm tắt chỉ số      | VCI only            |\n\n**Ứng Dụng:** Nghiên cứu công ty, phân tích quản trị, theo dõi thay đổi cấp quản lý\n\n---\n\n### 3. Finance API - Báo Cáo Tài Chính\n\n| Method               | Mô Tả                | Sources             |\n| -------------------- | -------------------- | ------------------- |\n| `income_statement()` | Báo cáo thu nhập     | KBS, VCI, TCBS, FMP |\n| `balance_sheet()`    | Bảng cân đối kế toán | KBS, VCI, TCBS, FMP |\n| `cash_flow()`        | Báo cáo dòng tiền    | KBS, VCI, TCBS, FMP |\n| `ratio()`            | Chỉ số tài chính     | KBS, VCI, TCBS, FMP |\n\n**Ứng Dụng:** Phân tích cơ bản, định giá công ty, so sánh ngành\n\n---\n\n### 4. Trading API - Dữ Liệu Giao Dịch\n\n| Method            | Mô Tả              | Sources        |\n| ----------------- | ------------------ | -------------- |\n| `price_board()`   | Bảng giá realtime  | KBS, VCI, TCBS |\n| `price_history()` | Lịch sử giá        | VCI only       |\n| `trading_stats()` | Thống kê giao dịch | VCI only       |\n| `side_stats()`    | Thống kê mua/bán   | VCI only       |\n\n**Ứng Dụng:** Theo dõi giá thị trường, phân tích dòng tiền\n\n---\n\n### 5. Listing API - Danh Sách Chứng Khoán\n\n| Method                  | Mô Tả                 | Sources            |\n| ----------------------- | --------------------- | ------------------ |\n| `all_symbols()`         | Tất cả mã chứng khoán | KBS, VCI, MSN, FMP |\n| `symbols_by_exchange()` | Mã theo sàn           | VCI only           |\n| `government_bonds()`    | Trái phiếu chính phủ  | VCI only           |\n| `indices()`             | Danh sách chỉ số      | VCI, MSN, FMP      |\n\n**Ứng Dụng:** Xây dựng danh sách chứng khoán, lọc theo tiêu chí\n\n---\n\n### 6. Misc/Utils - Dữ Liệu Tiện Ích\n\n| Module         | Mô Tả           | Source       |\n| -------------- | --------------- | ------------ |\n| `GoldPrice`    | Giá vàng        | Web scraping |\n| `ExchangeRate` | Tỷ giá ngoại tệ | Web scraping |\n\n**Ứng Dụng:** Theo dõi giá vàng, chuyển đổi tiền tệ\n\n---\n\n## 🔌 Nguồn Dữ Liệu & Connectors\n\n### Explorer (Web Scraping)\n\n| Nguồn       | Domain       | Hỗ Trợ                                    | Phương Pháp  | Trạng Thái      |\n| ----------- | ------------ | ----------------------------------------- | ------------ | --------------- |\n| **VCI**     | vci.com.vn   | Quote, Listing, Company, Finance, Trading | Web Scraping | ✅ Hoạt động    |\n| **KBS**     | kbsec.com.vn | Quote, Listing, Company, Finance, Trading | Web Scraping | ✅ Mới (v3.4.0) |\n| **MSN**     | msn.com      | Quote, Listing                            | Web Scraping | ✅ Hoạt động    |\n| **FMarket** | fmarket.vn   | Listing (Fund)                            | Web Scraping | ✅ Hoạt động    |\n| **TCBS**    | tcbs.com.vn  | Quote, Listing, Company, Finance, Trading | Web Scraping | ⚠️ Ngưng hỗ trợ  |\n\n### Connector (Official APIs)\n\n| API         | Domain                    | Đặc Điểm                   | Chi Phí  | Trạng Thái   |\n| ----------- | ------------------------- | -------------------------- | -------- | ------------ |\n| **FMP**     | financialmodelingprep.com | Dữ liệu tài chính toàn cầu | Freemium | ✅ Hoạt động |\n| **DNSE**    | dnse.vn                   | API giao dịch  | Miễn phí   | ✅ Hoạt động |\n| **Binance** | binance.com               | Dữ liệu crypto             | Miễn phí | 📋 Sắp tới  |\n\n---\n\n## 🛠️ Core Utilities\n\nVnstock cung cấp các utilities hỗ trợ:\n\n### Market Utilities (`core/utils/market.py`)\n\n- `trading_hours()` - Lấy giờ giao dịch\n- `is_trading_hour()` - Kiểm tra giờ giao dịch\n- `market_status()` - Trạng thái thị trường (preparing, real_time, settling, historical_only)\n\n### Interval Utilities (`core/utils/interval.py`)\n\n- Chuẩn hóa timeframe: `1D`, `1H`, `1m`, `5m`, `15m`, `30m`, `1W`, `1M`\n- Hỗ trợ aliases: `d`, `h`, `m`, `w`, `M`\n\n### Lookback Utilities (`core/utils/lookback.py`)\n\n- Xử lý lookback periods: `1M`, `3M`, `6M`, `1Y`, `3Y`, `5Y`, `100D`, v.v.\n\n### Transform Utilities (`core/utils/transform.py`)\n\n- Chuyển đổi format: Long ↔ Wide, DataFrame ↔ JSON\n\n### Validation & Auth\n\n- `validation.py` - Kiểm tra dữ liệu\n\n---\n\n## 📈 Các Loại Dữ Liệu Chi Tiết\n\n### 1. Dữ Liệu Giá (Quote Data)\n\n```\n- Giá lịch sử: Open, High, Low, Close, Volume\n- Dữ liệu trong ngày (Intraday)\n- Bảng giá realtime\n- Độ sâu giá (Price Depth / Order Book)\n```\n\n### 2. Dữ Liệu Danh Sách (Listing Data)\n\n```\n- Tất cả mã chứng khoán\n- Lọc theo sàn giao dịch (HOSE, HNX, UPCOM)\n- Lọc theo ngành (ICB Industries)\n- Lọc theo chỉ số (VN30, VNMID, VNSML, v.v.)\n- Futures, Bonds, Warrants, Funds\n```\n\n### 3. Dữ Liệu Công Ty (Company Data)\n\n```\n- Hồ sơ công ty\n- Thông tin cổ đông chính\n- Danh sách nhân viên quản lý\n- Công ty con & chi nhánh\n- Tin tức & sự kiện\n```\n\n### 4. Dữ Liệu Tài Chính (Financial Data)\n\n```\n- Báo cáo tài chính:\n  ├─ Bảng cân đối kế toán (Balance Sheet)\n  ├─ Báo cáo kết quản kinh doanh (Income Statement)\n  ├─ Lưu chuyển tiền tệ (Cash Flow)\n \n\nArchive v1.0.1: 28 files, 76988 bytes\n\nFiles: agents/openai.yaml (239b), references/capabilities.md (1125b), references/free_tier_playbook.md (891b), references/invocation_recipes.md (1285b), references/method_matrix.md (1190b), references/vnstock/01-overview.md (28095b), references/vnstock/02-installation.md (12228b), references/vnstock/03-listing-api.md (24904b), references/vnstock/04-company-api.md (21607b), references/vnstock/05-trading-api.md (9800b), references/vnstock/06-quote-price-api.md (13075b), references/vnstock/07-financial-api.md (25128b), references/vnstock/08-fund-api.md (5715b), references/vnstock/09-screener-api.md (215b), references/vnstock/10-connector-guide.md (11977b), references/vnstock/11-best-practices.md (14666b), references/vnstock/README.md (5901b), scripts/build_universe.py (3489b), scripts/catalog_vnstock.py (3439b), scripts/collect_fundamentals.py (3458b), scripts/collect_market_data.py (3471b), scripts/common.py (4475b), scripts/generate_report.py (2229b), scripts/invoke_vnstock.py (5084b), scripts/run_pipeline.py (2689b), scripts/score_stocks.py (2508b), SKILL.md (7047b), _meta.json (138b)\n\nArchive v1.0.0: 28 files, 76709 bytes\n\nFiles: agents/openai.yaml (239b), references/capabilities.md (1125b), references/free_tier_playbook.md (891b), references/invocation_recipes.md (1285b), references/method_matrix.md (1190b), references/vnstock/01-overview.md (28095b), references/vnstock/02-installation.md (12228b), references/vnstock/03-listing-api.md (24904b), references/vnstock/04-company-api.md (21607b), references/vnstock/05-trading-api.md (9800b), references/vnstock/06-quote-price-api.md (13075b), references/vnstock/07-financial-api.md (25128b), references/vnstock/08-fund-api.md (5715b), references/vnstock/09-screener-api.md (215b), references/vnstock/10-connector-guide.md (11977b), references/vnstock/11-best-practices.md (14666b), references/vnstock/README.md (5901b), scripts/build_universe.py (3489b), scripts/catalog_vnstock.py (3439b), scripts/collect_fundamentals.py (3458b), scripts/collect_market_data.py (3471b), scripts/common.py (4475b), scripts/generate_report.py (2229b), scripts/invoke_vnstock.py (5084b), scripts/run_pipeline.py (2689b), scripts/score_stocks.py (2508b), SKILL.md (6491b), _meta.json (138b)","readmeExcerpt":"Skill: Vnstock Free Expert Owner: teahann Summary: Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users r... Tags: latest:1.0.3 Version history: v1.0.3 | 2026-05-22T00:22:16.119Z | user Update Vietnam institutional stock skill system with D1 governance, trade decision policy, and harness agent guide. v1.0.2 | 2026-0","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"python scripts/catalog_vnstock.py --outdir ./outputs\npython scripts/invoke_vnstock.py --class-name Quote --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"VCB\"}' --method history --method-kwargs '{\"start\":\"2024-01-01\",\"end\":\"2024-12-31\",\"interval\":\"1D\"}' --outdir ./outputs\npython scripts/run_pipeline.py --source kbs --mode group --group VN30 --outdir ./outputs"},{"language":"bash","snippet":"pip install vnstock"},{"language":"text","snippet":"Ứng Dụng\n   ↓\nAPI Thống Nhất (Quote, Listing, Finance, Company)\n   ↓\nAdapter Layer (Chuẩn hóa dữ liệu)\n   ↓\nCác Nguồn Dữ Liệu (Web Scraping & API bên ngoài)"},{"language":"bash","snippet":"python /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Quote \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"VCB\"}' \\\n  --method history \\\n  --method-kwargs '{\"start\":\"2024-01-01\",\"end\":\"2024-12-31\",\"interval\":\"1D\"}' \\\n  --outdir ./outputs"},{"language":"bash","snippet":"python /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Company \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"FPT\"}' \\\n  --method overview \\\n  --method-kwargs '{}' \\\n  --outdir ./outputs"},{"language":"bash","snippet":"python /Users/teahan/Projects/vscode-workspace/vn_stock_skill/skills/vnstock-free-expert/scripts/invoke_vnstock.py \\\n  --class-name Finance \\\n  --init-kwargs '{\"source\":\"kbs\",\"symbol\":\"ACB\"}' \\\n  --method ratio \\\n  --method-kwargs '{\"period\":\"year\"}' \\\n  --outdir ./outputs"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: vnstock-free-expert\ndescription: Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users request Vietnamese stock analysis under free-tier constraints.\ncompatibility: Requires Python 3.x, vnstock package, pandas, internet access, and optional VNSTOCK_API_KEY in .env.\n---\n\n# VNStock Free Expert\n\nUse this skill when the user needs advanced Vietnam stock analysis with `vnstock`, while staying safe on free-tier limits.\n\n## Important packaging note\nThis skill is self-contained and does not require shipping a separate `vnstock/` docs folder.\nAll operational knowledge needed by the agent is stored under:\n- `references/`\n\n## Read order\n1. Read `references/capabilities.md`.\n2. Read `references/method_matrix.md` for exact class/method mapping.\n3. Read `references/free_tier_playbook.md` before large runs.\n\n## Scope and constraints\n- Library: `vnstock` only.\n- Preferred sources: `kbs` first, `vci` fallback.\n- Never use `tcbs`.\n- Treat `Screener API` as unavailable unless user confirms it is restored in their installed version.\n\n## Free-tier operating rules\n- No API key: target <= 20 requests/minute.\n- Free API key: target <= 60 requests/minute.\n- Safe default pacing in scripts: 3.2s/request.\n- Reuse cached artifacts between steps.\n\n## Shared confidence rubric (required)\nReport confidence as `High` / `Medium` / `Low` using this standard:\n- `High`: universe coverage >= 95%, critical metrics coverage >= 80%, and hard errors <= 5% of symbols.\n- `Medium`: universe coverage >= 80%, critical metrics coverage >= 60%, and hard errors <= 15%.\n- `Low`: below `Medium` thresholds or material missing fields that can flip ranking results.\n\nAlways output:\n1. Confidence level.\n2. Coverage stats (`symbols_requested`, `symbols_scored`, `% missing by key metric`).\n3. Top missing fields that may change conclusions.\n\n## API key configuration (implemented)\n- Skill-local key file: `.env`\n- Variable: `VNSTOCK_API_KEY`\n- All API-calling scripts auto-load this key and call vnstock auth setup before requests.\n- You can override per run with `--api-key \"...\"`.\n\n## Execution workflow (ordered)\n1. Validate environment (`python`, `vnstock`, `pandas`) and load optional API key from `.env`.\n2. Build a universe using `scripts/build_universe.py` (`group`, `exchange`, or `symbols` mode).\n3. Collect market data with `scripts/collect_market_data.py` using safe pacing.\n4. Collect fundamentals with `scripts/collect_fundamentals.py`.\n5. Score and rank using `scripts/score_stocks.py`.\n6. Generate analyst-style memo with `scripts/generate_report.py`.\n7. Apply confidence rubric, disclose missing fields, and summarize risks.\n\n## Downstream handoff bundle (required when doing single-ticker deep dive)\nWhen the user request is about valuing or building a memo for a **specific ticker** (or a small list), output a compact JSON bundle that downstream skills can reuse:\n- `ticker`, `as_of_date`, `curren"},{"path":"references/vnstock/README.md","content":"# VNStock 3.4.0 - Tài Liệu Hướng Dẫn\n\n## 🎯 Giới Thiệu\n\n**VNStock** là thư viện Python để lấy dữ liệu chứng khoán Việt Nam từ nhiều nguồn uy tín. Thiết kế với kiến trúc provider-based, cho phép chuyển đổi linh hoạt giữa các nguồn dữ liệu khác nhau.\n\n### ✨ Tính Năng Chính\n\n- ✅ **Nhiều nguồn dữ liệu**: VCI, KBS, MSN (API công khai); FMP, DNSE (API chính thức)\n- ⚠️ **TCBS**: Ngưng cập nhật thêm từ v3.4.0, sẽ loại bỏ trong v3.5.0 (tháng 3/2026)\n- ✅ **API thống nhất**: Cùng interface cho tất cả nguồn\n- ✅ **Dữ liệu lịch sử & Real-time**: Giá, công ty, tài chính\n- ✅ **Dữ liệu công ty**: Hồ sơ, cổ đông, nhân viên quản lý\n- ✅ **Dữ liệu tài chính**: Báo cáo, chỉ số, lưu chuyển tiền tệ\n- ✅ **Lọc & Phân loại**: Theo ngành, sàn giao dịch, chỉ số\n\n## 📚 Hướng Dẫn Sử Dụng\n\n| Tài Liệu | Nội Dung | Mức Độ |\n|---------|---------|--------|\n| **[01-Overview](01-overview.md)** | Tổng quan kiến trúc, các loại dữ liệu | Cơ bản |\n| **[02-Installation](02-installation.md)** | Cài đặt, thiết lập, kiểm tra | Cơ bản |\n| **[03-Listing API](03-listing-api.md)** | API tìm kiếm và lọc chứng khoán | Cơ bản |\n| **[04-Company API](04-company-api.md)** | Thông tin công ty, cổ đông, nhân viên quản lý | Cơ bản |\n| **[05-Trading API](05-trading-api.md)** | Dữ liệu giao dịch, bid/ask, thống kê | Cơ bản |\n| **[06-Quote & Price](06-quote-price-api.md)** | API lấy giá lịch sử và real-time | Cơ bản |\n| **[07-Financial API](07-financial-api.md)** | API dữ liệu tài chính và báo cáo | Trung cấp |\n| **[08-Fund API](08-fund-api.md)** | Dữ liệu quỹ đầu tư mở (Fmarket) | Trung cấp |\n| **[09-Screener API](09-screener-api.md)** | Công cụ lọc chứng khoán nâng cao | Nâng cao |\n| **[10-Connector Guide](10-connector-guide.md)** | Hướng dẫn API bên ngoài (FMP, XNO, DNSE) | Nâng cao |\n| **[11-Best Practices](11-best-practices.md)** | Mẹo tối ưu hóa, xử lý lỗi, security | Nâng cao |\n\n## 🚀 Bắt Đầu Nhanh\n\n### Cài Đặt\n\n```bash\npip install vnstock\n```\n\nXem chi tiết tại **[02-Installation](02-installation.md)**\n\n## 📖 Cấu Trúc Tài Liệu\n\nTài liệu được chia thành 11 phần theo thứ tự từ cơ bản đến nâng cao:\n\n1. **[01-Overview](01-overview.md)** - Hiểu kiến trúc và các loại dữ liệu\n2. **[02-Installation](02-installation.md)** - Cài đặt và kiểm tra môi trường\n3. **[03-Listing API](03-listing-api.md)** - Tìm kiếm danh sách chứng khoán\n4. **[04-Company API](04-company-api.md)** - Lấy thông tin công ty chi tiết\n5. **[05-Trading API](05-trading-api.md)** - Dữ liệu giao dịch thị trường\n6. **[06-Quote & Price](06-quote-price-api.md)** - Lấy dữ liệu giá\n7. **[07-Financial API](07-financial-api.md)** - Truy cập dữ liệu tài chính\n8. **[08-Fund API](08-fund-api.md)** - Thông tin quỹ đầu tư mở\n9. **[09-Screener API](09-screener-api.md)** - Lọc chứng khoán nâng cao\n10. **[10-Connector Guide](10-connector-guide.md)** - Sử dụng API bên ngoài\n11. **[11-Best Practices](11-best-practices.md)** - Tối ưu hóa và xử lý lỗi\n\n## Kiến Trúc Hệ Thống\n\nVNStock sử dụng kiến trúc provider-based cho phép chuyển đổi linh hoạt giữa các nguồn dữ "},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7aqz9b9xv2mmyvsg54n5kecn81kkaf\",\n  \"slug\": \"vnstock-free-expert\",\n  \"version\": \"1.0.3\",\n  \"publishedAt\": 1779409336119\n}"},{"path":"references/capabilities.md","content":"# VNStock Capability Reference (Self-Contained)\n\n## Core capabilities\n- Symbol universe and classification: exchanges, industries, index groups, derivatives/bonds/warrants listings.\n- Company intelligence: overview, shareholders, officers, subsidiaries, affiliates, events, reports (source-dependent).\n- Market data: historical OHLCV, intraday prints, board snapshots, market depth (source-dependent).\n- Financial statements and ratios: income statement, balance sheet, cash flow, ratio with period modes.\n- Fund data: investment fund listings and related metadata.\n- External connectors: available depending on environment and API keys.\n\n## Source strategy\n- Primary source: `kbs`.\n- Secondary fallback: `vci`.\n- Do not use `tcbs`.\n\n## Data caveats\n- Method availability differs by source.\n- Some methods may return empty frames for specific symbols/time windows.\n- Realtime/near-realtime outputs depend on market hours and provider freshness.\n\n## Safe analysis pattern\n1. Fetch raw data.\n2. Validate shape/columns.\n3. Handle empty/missing values.\n4. Compute derived metrics.\n5. Separate factual output from interpretation."},{"path":"references/free_tier_playbook.md","content":"# Free-Tier Playbook\n\n## Rate limit profile\n- Guest/no key: 20 requests/minute.\n- Free key: up to 60 requests/minute.\n\n## Execution controls\n- Default minimum interval: 3.2 seconds/request.\n- For unstable network/provider: increase to 4-5 seconds/request.\n- Process symbols in chunks (e.g. 20-50 symbols/batch).\n\n## Resilience checklist\n- Retry transient failures with backoff.\n- Log per-symbol failures; do not fail the whole run if a single symbol fails.\n- Save intermediate artifacts (`universe`, `market_data`, `fundamentals`) for resume.\n\n## Data quality checklist\n- Confirm expected columns exist before calculation.\n- Track missing metrics ratio.\n- Flag stale data windows and low-bar histories.\n\n## Portfolio-analysis checklist\n- Use relative ranking, not absolute threshold only.\n- Validate top picks against recent macro/news context.\n- Apply sector diversification and risk caps."}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users r... Skill: Vnstock Free Expert Owner: teahann Summary: Runs an end-to-end vnstock workflow for free-tier-safe Vietnam stock valuation, ranking, and API operations with strict rate-limit control; used when users r... Tags: latest:1.0.3 Version history: v1.0.3 | 2026-05-22T00:22:16.119Z | user Update Vietnam institutional stock skill system with D1 governance, trade decision policy, and harness agent guide. v1.0.2 | 2026-0","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1561,"uniquenessScore":48,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-10T00:25:58.054Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-10T00:25:58.054Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:55:12.987Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}