Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Vnstock
https://github.com/vnstock-hq/vnstock-agent-guide
Admin
Vnstock is a comprehensive Python library for accessing Vietnamese stock market data and financial
...
Tokens:
36,796
Snippets:
261
Trust Score:
6.2
Update:
1 week ago
Context
Skills
Chat
Benchmark
91.2
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# VnStock Agent Guide VnStock Agent Guide is a comprehensive documentation repository designed specifically for AI Agents (Claude, Gemini, GitHub Copilot, Cursor, Windsurf) to provide accurate, up-to-date guidance on using the VnStock Python library ecosystem for Vietnamese stock market data. The ecosystem consists of five core libraries: `vnstock` (free tier for basic market data), `vnstock_data` (sponsor tier with advanced features and Unified UI), `vnstock_ta` (technical analysis indicators), `vnstock_news` (news crawling and sentiment analysis), and `vnstock_pipeline` (data pipelines and real-time streaming). The library supports multiple data sources including KBS (recommended for stability), VCI (comprehensive data), and others, providing access to stock quotes, company information, financial statements, macroeconomic data, market insights, and more. The Unified UI introduced in `vnstock_data` v3.0.0 offers a chained API design with seven data layers: Reference, Market, Fundamental, Analytics, Macro, Insights, and News, making it easier to access the full breadth of Vietnamese market data programmatically. --- ## Installation Install the vnstock library from PyPI for the free tier functionality. ```bash # Install from PyPI (stable) pip install vnstock # Install from GitHub (latest development) pip install git+https://github.com/vnstock-lab/vnstock.git # Dependencies are automatically installed: # pandas>=1.3.0, requests>=2.25.0, beautifulsoup4>=4.9.0, lxml>=4.6.0 # pydantic>=1.8.0, tenacity>=8.0.0, aiohttp>=3.7.0, tqdm>=4.60.0 ``` --- ## API Key Registration and Authentication VnStock supports different usage tiers with corresponding rate limits. Register for a free API key to increase your request quota from 20 to 60 requests per minute. ```python from vnstock.core.utils.auth import register_user, change_api_key, check_status # Interactive registration - will guide you to https://vnstocks.com/login register_user() # Change API key if needed change_api_key("your_api_key_here") # Check current status status = check_status() # Output: # API key: ab12***ef34 # Tier: Community # Limit: 60 requests/minute # After registration, API key is automatically used for all requests from vnstock import Quote quote = Quote(source="KBS", symbol="VCI") df = quote.history(start="2024-01-01", end="2024-12-31") ``` --- ## Listing API - Stock Discovery and Filtering The Listing API provides methods to search, filter, and retrieve information about securities available on the market including stocks, indices, bonds, warrants, and ETFs. ```python from vnstock import Listing # Initialize with KBS source (recommended for stability) listing = Listing(source="KBS") # Get all stock symbols all_symbols = listing.all_symbols(to_df=True) print(f"Total symbols: {len(all_symbols)}") # ~1565 symbols # Columns: ['symbol', 'organ_name'] # Get as list instead of DataFrame symbols_list = listing.all_symbols(to_df=False) print(symbols_list[:5]) # ['DPP', 'SDA', 'SDC', 'SDH', 'SDS'] # Filter by exchange (HOSE, HNX, UPCOM) hose_stocks = listing.symbols_by_exchange(exchange="HOSE", to_df=True) print(f"HOSE stocks: {len(hose_stocks)}") # Columns: ['symbol', 'organ_name', 'en_organ_name', 'exchange', 'type', 'id'] # Filter by industry classification (ICB) by_industry = listing.symbols_by_industries() # Get VN30 index components vn30 = listing.symbols_by_group(group="VN30") print(vn30) # Returns Series with 30 symbols # Get all indices indices = listing.all_indices() # Get ETFs (KBS exclusive) etfs = listing.all_etf() # Get bonds and warrants bonds = listing.all_bonds() warrants = listing.all_covered_warrant() ``` --- ## Quote API - Historical and Real-time Price Data The Quote API provides historical OHLCV data, intraday tick data, and order book depth information for stocks, indices, and other securities. ```python from vnstock import Quote # Initialize Quote adapter quote = Quote(symbol="VCI", source="VCI") # Get historical OHLCV data with date range df = quote.history(start="2024-01-01", end="2024-12-31", interval="1D") print(df[['time', 'open', 'high', 'low', 'close', 'volume']].head()) # Output: # time open high low close volume # 0 2024-01-02 32.10 32.50 31.80 32.30 1234567 # Use length parameter for lookback periods df_1m = quote.history(length="1M", interval="1D") # Last 1 month df_3m = quote.history(length="3M", interval="1D") # Last 3 months (90 days) df_1y = quote.history(length="1Y", interval="1D") # Last 1 year df_100 = quote.history(length=100, interval="1D") # Last 100 days df_50b = quote.history(length="50b", interval="1D") # Last 50 bars/candles # Supported intervals: 1m, 5m, 15m, 30m, 1H, 1D, 1W, 1M # Aliases: m (minute), h (hour), d (day), w (week), M (month) # Get intraday tick data intraday = quote.intraday(page_size=100) print(intraday[['time', 'price', 'volume', 'match_type']].head()) # Output: # time price volume match_type # 0 09:00:05.123 32.50 1000 BU # Get order book / price depth (VCI only) depth = quote.price_depth() print(depth) # Shows bid/ask levels with prices and volumes ``` --- ## Trading API - Real-time Price Board The Trading API provides real-time market price board data including current prices, bid/ask levels, and trading statistics for multiple symbols at once. ```python from vnstock import Trading # Initialize with KBS (29 columns, standardized) trading = Trading(source="KBS", symbol="VCI") # Get price board for multiple symbols board = trading.price_board(symbols_list=['VCI', 'VCB', 'ACB', 'HPG', 'FPT']) print(f"Shape: {board.shape}") # (5, 29) # Key columns available print(board[['symbol', 'exchange', 'reference_price', 'price_change', 'percent_change']]) # Output: # symbol exchange reference_price price_change percent_change # 0 VCI HOSE 34850 -50 -0.1435 # 1 VCB HOSE 84500 100 0.1183 # Access bid/ask data print(board[['symbol', 'bid_price_1', 'bid_vol_1', 'ask_price_1', 'ask_vol_1']]) # Filter stocks by conditions risers = board[board['price_change'] > 0] high_volume = board[board['volume_accumulated'] > 1000000] # VCI source provides more detailed data (77 columns) trading_vci = Trading(source="VCI", symbol="VCI") board_vci = trading_vci.price_board(symbols_list=['VCI', 'VCB']) print(board_vci[['symbol', 'ref_price', 'match_price', 'total_volume']]) ``` --- ## Company API - Corporate Information The Company API provides comprehensive company information including profiles, shareholders, management, subsidiaries, news, and events. ```python from vnstock import Company # Initialize with KBS (recommended) company = Company(source="KBS", symbol="VCI") # Get company overview (30 columns with KBS) overview = company.overview() print(overview[['symbol', 'charter_capital', 'exchange', 'number_of_employees']]) # Output: # symbol charter_capital exchange number_of_employees # 0 VCI 8501000000000 HOSE 850 # Get major shareholders shareholders = company.shareholders() print(shareholders[['name', 'shares_owned', 'ownership_percentage']]) # Output: # name shares_owned ownership_percentage # 0 To Hai 128889403 17.95 # Get company officers/management officers = company.officers() print(officers[['name', 'position', 'from_date']]) # Output: # name position from_date # 0 To Hai Chairman of the Board 2007 # Get subsidiaries subsidiaries = company.subsidiaries() # Get company news with pagination (KBS feature) news = company.news(page=1, page_size=10) # Get corporate events events = company.events() # KBS-exclusive methods ownership = company.ownership() # Ownership structure capital_history = company.capital_history() # Capital changes insider = company.insider_trading() # Insider transactions ``` --- ## Finance API - Financial Statements The Finance API provides access to financial reports including income statements, balance sheets, cash flow statements, and financial ratios. ```python from vnstock import Finance # Initialize Finance adapter finance = Finance(source="KBS", symbol="VCI") # Get income statement (quarterly data) income = finance.income_statement(period="quarter") print(f"Shape: {income.shape}") # (90, 10) - 90 line items print(income.columns) # ['item', 'item_id', 'unit', 'levels', 'row_number', '2025-Q3', '2025-Q2', ...] # Get yearly income statement income_year = finance.income_statement(period="year") # Display mode options for field names from vnstock.explorer.kbs.financial import FieldDisplayMode # Standardized (Vietnamese only) df_std = finance.income_statement(period="quarter", display_mode=FieldDisplayMode.STD) # All fields (Vietnamese + English + item_id) df_all = finance.income_statement(period="quarter", display_mode=FieldDisplayMode.ALL) # English only df_en = finance.income_statement(period="quarter", display_mode='en') # Get balance sheet (162 line items) balance = finance.balance_sheet(period="quarter") # Get cash flow statement (159 line items) cashflow = finance.cash_flow(period="quarter") # Get financial ratios (27 ratios with KBS) ratios = finance.ratio(period="quarter") print(ratios[ratios['item_id'].isin(['roe', 'roa', 'eps', 'pe'])]) ``` --- ## Unified UI - Reference Layer (vnstock_data) The Reference Layer in the Unified UI provides static reference data about companies, equities, indices, industries, funds, bonds, and market events. ```python from vnstock_data import Reference ref = Reference() # === Company Information === # Get company profile profile = ref.company("TCB").info() print(profile) # Get major shareholders shareholders = ref.company("VIC").shareholders() print(shareholders) # Get company officers officers = ref.company("HPG").officers() # Get subsidiaries subsidiaries = ref.company("VNM").subsidiaries() # Get company news and events news = ref.company("TCB").news() events = ref.company("TCB").events() # === Equity Listings === # All equities (1700+ symbols) all_equities = ref.equity.list() print(f"Total: {len(all_equities)}") # Filter by index group vn30 = ref.equity.list_by_group("VN30") # Filter by exchange by_exchange = ref.equity.list_by_exchange() # Filter by industry by_industry = ref.equity.list_by_industry() # === Index Information === indices = ref.index.list() index_groups = ref.index.groups() vn30_members = ref.index.members("VN30") vn30_info = ref.index("VN30").info() # === Other Reference Data === industries = ref.industry.list() funds = ref.fund.list() etfs = ref.etf.list() bonds = ref.bond.list(bond_type='all') # 'corporate' or 'government' events_calendar = ref.events.calendar(start='2026-03-01', end='2026-03-31') futures = ref.futures().list() warrants = ref.warrant().list() ``` --- ## Unified UI - Market Layer (vnstock_data) The Market Layer provides real-time and historical trading data including OHLCV, order books, trades, foreign flow, and market statistics. ```python from vnstock_data import Market mkt = Market() # === Equity Market Data === # Historical OHLCV data ohlcv = mkt.equity("VIC").ohlcv(start="2026-02-01", end="2026-03-01") print(ohlcv) # Columns: ['time', 'open', 'high', 'low', 'close', 'volume'] # Trading history statistics history = mkt.equity("VIC").trade_history(start="2026-02-01", end="2026-03-01") # Intraday trades (Time & Sales) trades = mkt.equity("TCB").trades() # Order book depth orderbook = mkt.equity("VNM").order_book() # Current quote / price board quote = mkt.equity("HPG").quote() # Session statistics session = mkt.equity("VIC").session_stats() # Foreign investor flow foreign = mkt.equity("VIC").foreign_flow() # Proprietary trading flow proprietary = mkt.equity("VIC").proprietary_flow() # Block trades (negotiated deals) blocks = mkt.equity("VIC").block_trades() # Volume profile vol_profile = mkt.equity("VJC").volume_profile() # Summary information summary = mkt.equity("VIC").summary() # === Index Market Data === vnindex = mkt.index("VNINDEX").ohlcv(start="2026-01-01", end="2026-03-01") index_quote = mkt.index("VNINDEX").quote() # === Multi-symbol Quote === quotes = mkt.quote(['VCI', 'VCB', 'ACB', 'HPG']) # === Other Markets === # Futures, warrants, ETFs, funds futures_data = mkt.futures("VN30F2503").ohlcv(start="2026-01-01", end="2026-03-01") etf_data = mkt.etf("E1VFVN30").ohlcv(start="2026-01-01", end="2026-03-01") fund_nav = mkt.fund("DCDS").nav_history() # International markets crypto = mkt.crypto("BTCUSDT").ohlcv(length="1M") forex = mkt.forex("EURUSD").ohlcv(length="1M") commodity = mkt.commodity("XAUUSD").ohlcv(length="1M") ``` --- ## Unified UI - Fundamental Layer (vnstock_data) The Fundamental Layer provides financial statement data and ratios for fundamental analysis, with support for auto-scoring based on industry classification. ```python from vnstock_data import Fundamental fun = Fundamental() # === Financial Statements === # Income statement (4 recent periods) income = fun.equity("TCB").income_statement(limit=4) print(income) # Balance sheet - using utility function syntax balance = fun.equity.balance_sheet("VIC", limit=4) # Cash flow statement cashflow = fun.equity("VNM").cash_flow(limit=4) # Financial ratios (PE, PB, ROE, Debt/Equity, etc.) ratios = fun.equity("HPG").ratio(limit=4) # BCTC Notes (detailed footnotes) notes = fun.equity("FPT").note() # === Financial Health Scorecard === # Auto-detect industry and apply appropriate scorecard health_auto = fun.equity("SSI").financial_health( scorecard="auto", # auto, banking, securities, insurance, generic lang="vi", limit=4 ) # Force banking scorecard for bank analysis health_bank = fun.equity("TCB").financial_health( scorecard="banking", lang="en", limit=4 ) # Parameters: # - limit: Number of periods (quarters/years) # - period_type: 1=Year, 2=Quarter # - lang: "vi" (Vietnamese) or "en" (English) # - scorecard: "auto", "banking", "securities", "insurance", "generic" ``` --- ## Unified UI - Macro Layer (vnstock_data) The Macro Layer provides macroeconomic data including GDP, CPI, FDI, exchange rates, interest rates, and commodity prices. ```python from vnstock_data import Macro mac = Macro() # === Economy Data (Vietnam) === # GDP growth gdp_quarterly = mac.economy().gdp(start="2020-01", end="2026-03", period="quarter") gdp_yearly = mac.economy().gdp(period="year") # Consumer Price Index cpi = mac.economy().cpi(period="month", length=24) # Last 24 months # Industrial production industry = mac.economy().industry_prod(period="month", length=12) # Import/Export trade balance trade = mac.economy().import_export(period="month") # Retail sales retail = mac.economy().retail(period="month") # Foreign Direct Investment fdi = mac.economy().fdi(period="month") # Money supply money = mac.economy().money_supply(period="month") # Population and labor statistics labor = mac.economy().population_labor(period="year") # === Currency & Interest Rates === # Daily exchange rates exchange = mac.currency().exchange_rate( start="2026-02-06", end="2026-03-06", period="day" ) print(exchange[['report_time', 'USD', 'EUR', 'JPY']]) # Monthly average exchange rates exchange_monthly = mac.currency().exchange_rate(period="month", length=12) # Interest rates interest = mac.currency().interest_rate(period="day", length=365) # === Commodity Prices === # Gold prices gold = mac.commodity().gold(length="1M") # Oil prices oil = mac.commodity().oil(length="3M") # Steel, agriculture, etc. steel = mac.commodity().steel(length="6M") ``` --- ## Unified UI - Insights Layer (vnstock_data) The Insights Layer provides stock rankings and screening tools to identify trading opportunities and market trends. ```python from vnstock_data import Insights ins = Insights() # === Stock Rankings === # Top gainers (price increase) gainers = ins.ranking().gainer(limit=10) gainers_vn = ins.ranking().gainer(index='VNINDEX', limit=10) # Top losers (price decrease) losers = ins.ranking().loser(limit=10) # Top by trading volume volume = ins.ranking().volume(limit=10) # Top by trading value value = ins.ranking().value(limit=10) # Top foreign buying foreign_buy = ins.ranking().foreign_buy(limit=10) # Top foreign selling foreign_sell = ins.ranking().foreign_sell(limit=10) # Top block trades (negotiated deals) deals = ins.ranking().deal(limit=10) # === Stock Screener === # Get available screening criteria criteria = ins.screener().criteria(lang='vi') print(criteria) # Screen stocks with custom filters params = { "filter": [ {"name": "exchange", "conditionOptions": [{"type": "value", "value": "hsx"}]}, {"name": "marketCap", "conditionOptions": [{"from": 1e12, "to": 1e14}]}, {"name": "ttmPe", "conditionOptions": [{"from": 5, "to": 15}]}, {"name": "ttmRoe", "conditionOptions": [{"from": 15, "to": 50}]}, {"name": "rsi", "conditionOptions": [{"from": 30, "to": 70}]} ] } screened = ins.screener().filter(params=params, limit=100) print(screened) # Filter criteria include: # - exchange, sectorLv1, marketCap, marketPrice # - dailyPriceChangePercent, adtv, avgVolume, priceReturn # - stockStrength, rs, rsi, priceEma, macd, adx # - ttmPe, ttmPb, ttmRoe, debtToEquity, epsGrowth ``` --- ## Technical Analysis (vnstock_ta) The vnstock_ta library provides 25+ technical indicators for trend analysis, momentum, volatility, and volume analysis. ```python from vnstock_data import Market from vnstock_ta import Indicator # Get OHLCV data mkt = Market() df = mkt.equity("VCB").ohlcv(start="2024-09-01", end="2024-12-02") df = df.set_index('time') # Initialize indicator calculator indicator = Indicator(data=df) # === Trend Indicators === # Simple Moving Average sma_20 = indicator.sma(length=20) sma_50 = indicator.sma(length=50) # Exponential Moving Average ema_12 = indicator.ema(length=12) ema_26 = indicator.ema(length=26) # Volume Weighted Average Price vwap = indicator.vwap(anchor='D') # Daily VWAP # Volume Weighted Moving Average vwma = indicator.vwma(length=20) # === Momentum Indicators === # Relative Strength Index rsi = indicator.rsi(length=14) # MACD macd = indicator.macd(fast=12, slow=26, signal=9) # Returns DataFrame with columns: MACD, MACD_signal, MACD_hist # Stochastic stoch = indicator.stochastic(k=14, d=3, smooth_k=3) # Returns DataFrame with columns: %K, %D # === Volatility Indicators === # Bollinger Bands bb = indicator.bollinger_bands(length=20, std=2) # Returns DataFrame with columns: BBL, BBM, BBU, BBB, BBP # Average True Range atr = indicator.atr(length=14) # === Volume Indicators === # On-Balance Volume obv = indicator.obv() # Money Flow Index mfi = indicator.mfi(length=14) # Add indicators to DataFrame df['SMA_20'] = sma_20 df['RSI'] = rsi df['MACD'] = macd['MACD'] print(df[['close', 'SMA_20', 'RSI', 'MACD']].tail()) ``` --- ## News Crawling (vnstock_news) The vnstock_news library provides tools to crawl financial news from Vietnamese news sources via RSS feeds and sitemaps. ```python from vnstock_news import Crawler, BatchCrawler, AsyncBatchCrawler import pandas as pd # === Basic Crawler (RSS + Sitemap) === crawler = Crawler(site_name="vnexpress") # Get articles from RSS feed articles = crawler.get_articles_from_feed(limit_per_feed=10) df = pd.DataFrame(articles) print(df[['url', 'title', 'publish_time', 'source']].head()) # Get articles (RSS first, fallback to sitemap) articles = crawler.get_articles(limit=100) # Custom config for new sites custom_config = { "name": "My Custom News", "domain": "mynews.com", "rss_urls": ["https://mynews.com/feed.xml"], "sitemap_url": "https://mynews.com/sitemap.xml", "config": {"title_selector": {"class": "title"}} } custom_crawler = Crawler(custom_config=custom_config) # === Batch Crawler (with resume support) === batch = BatchCrawler( site_name="cafef", request_delay=1.5, # Delay between requests output_path="./data", # Output directory debug=False ) # Fetch article details in batch articles = batch.fetch_articles(limit=100) # Fetch from specific sitemap articles = batch.fetch_articles( sitemap_url="https://cafef.vn/latest-news-sitemap.xml", limit=500 ) # === Async Batch Crawler (high performance) === async_crawler = AsyncBatchCrawler( site_name="cafef", max_concurrent=5, # Concurrent requests request_delay=0.5 ) # Async fetch import asyncio articles = asyncio.run(async_crawler.fetch_articles(limit=1000)) ``` --- ## Data Pipeline (vnstock_pipeline) The vnstock_pipeline library provides a framework for building data pipelines with fetching, validation, transformation, and export stages. ```python from vnstock_pipeline.tasks.ohlcv import run_task from vnstock_pipeline.tasks.financial import run_financial_task from vnstock_pipeline.tasks.intraday import run_intraday_task from vnstock_pipeline.tasks.price_board import run_price_board_task # === OHLCV Pipeline === # Fetch historical price data for multiple symbols tickers = ['VCB', 'ACB', 'HPG', 'FPT', 'VNM'] run_task( tickers, start="2024-01-01", end="2024-12-31", interval="1D" ) # Output: ./data/ohlcv/VCB.csv, ./data/ohlcv/ACB.csv, ... # === Financial Pipeline === # Fetch financial reports for multiple companies run_financial_task( tickers=['VCB', 'ACB'], balance_sheet_period="year", income_statement_year_period="year", lang="vi", output_dir="./data/financial" ) # Output: ./data/financial/VCB_balance_sheet.csv, etc. # === Intraday Pipeline === run_intraday_task( tickers=['VCB', 'ACB'], output_dir="./data/intraday" ) # === Price Board Pipeline === run_price_board_task( tickers=['VCB', 'ACB', 'HPG'], output_dir="./data/price_board" ) # === Custom Pipeline with Scheduler === from vnstock_pipeline.core.scheduler import Scheduler from vnstock_pipeline.template.vnstock import VNFetcher, VNValidator, VNTransformer from vnstock_pipeline.core.exporter import CSVExporter scheduler = Scheduler( fetcher=VNFetcher(), validator=VNValidator(), transformer=VNTransformer(), exporter=CSVExporter(output_dir="./data") ) # Run for list of symbols with parallel processing results = scheduler.run( symbols=['VCB', 'ACB', 'HPG', 'FPT'], params={'start': '2024-01-01', 'end': '2024-12-31'} ) ``` --- ## Real-time Streaming (vnstock_pipeline) The streaming module provides WebSocket-based real-time data streaming with low latency for the entire market. ```python from vnstock_pipeline.stream.client import WSSClient from vnstock_pipeline.stream.processors import QuoteProcessor, TradeProcessor # Initialize WebSocket client client = WSSClient() # Define callback for quote updates def on_quote(data): print(f"Quote: {data['symbol']} - Price: {data['price']}") # Define callback for trade updates def on_trade(data): print(f"Trade: {data['symbol']} - {data['volume']} @ {data['price']}") # Subscribe to symbols client.subscribe( symbols=['VCB', 'ACB', 'HPG'], on_quote=on_quote, on_trade=on_trade ) # Start streaming (blocking) client.start() # Or run in background import threading thread = threading.Thread(target=client.start) thread.daemon = True thread.start() # Unsubscribe when done client.unsubscribe(['VCB']) client.stop() ``` --- ## Summary The VnStock ecosystem provides a comprehensive toolkit for Vietnamese stock market data analysis, supporting use cases ranging from individual research to production trading systems. For basic data access, the free `vnstock` library offers Quote, Listing, Company, Finance, and Trading APIs with KBS and VCI data sources. For advanced features, sponsor-tier libraries unlock the Unified UI with seven data layers (Reference, Market, Fundamental, Analytics, Macro, Insights), technical indicators via vnstock_ta, news crawling via vnstock_news, and production-grade pipelines with real-time streaming via vnstock_pipeline. Integration patterns typically follow a layered approach: use Reference layer for static lookups (symbols, companies, indices), Market layer for price data and trading activity, Fundamental layer for financial analysis, Insights layer for screening and rankings, and Macro layer for economic context. For production deployments, vnstock_pipeline's scheduler handles parallel processing of 1600+ symbols with automatic retry logic, while the streaming module enables real-time monitoring. The libraries support multiple output formats (DataFrame, CSV, Parquet, DuckDB) and integrate seamlessly with pandas, making it easy to build custom analysis workflows, backtesting systems, and trading dashboards for the Vietnamese market.