vnstock

repository·main·Indexed 23 days ago

https://github.com/thinh-vu/vnstock

An open-source Python toolkit for extracting and analyzing financial data from the Vietnamese stock market. Version 4.0.5 introduces a Unified UI with Market, Reference, and Fundamental classes to access historical prices, company profiles, and financial statements. The library covers equities, indices, warrants, futures, funds, ETFs, and macro data (Forex, Gold, Crypto). It supports user authentication via API keys to increase request limits and provides a dedicated Agent Guide for AI coding assistants.

Tokens
20.5K
Snippets
83
Records
133
Agent score
79%

What's inside vnstock

  1. Overview of Vnstock data categories

    main

    Vnstock provides comprehensive data coverage across six main categories:

    1. Equity (Cổ phiếu): Real-time stock prices, historical price data, financial statements, and company profiles.
    2. Index (Chỉ số thị trường): Historical data for VNINDEX, HNX, UPCOM, and industry indices.
    3. Warrant (Chứng quyền): Warrant information, actual prices, maturity dates, and trading status.
    4. Futures (Phái sinh): VN30 futures contracts and corresponding terms.
    5. Fund & ETF (Quỹ đầu tư): Portfolio information, FMarket open fund performance, and ETFs.
    6. Macro & Commodities (Vĩ mô & Hàng hóa): Forex rates, Gold prices (SJC), and Crypto.
  2. How ProxyManager works for network and rate limit management

    main

    The ProxyManager utility is designed to handle network restrictions, ISP blocks, rate limiting, and IP rotation. It follows a lifecycle of Fetch (getting fresh proxies from APIs like Proxyscrape), Test (validating connectivity and measuring response times), Select (choosing optimal proxies based on speed), and Rotate (switching proxies automatically to distribute traffic). It supports HTTP, HTTPS, and SOCKS5 protocols and can be integrated with common libraries like requests, aiohttp, or scrapy.

    from vnstock.core.utils.proxy_manager import ProxyManager
    
    # Initialize manager
    manager = ProxyManager(timeout=10)
    
    # Fetch 5 free proxies
    proxies = manager.fetch_proxies(limit=5)
    
    # View available proxies
    manager.print_proxies(proxies)
  3. Use the Unified UI (Vnstock v4+)

    main

    In Vnstock v4+, the API is organized into a Unified UI using three main classes: Market, Reference, and Fundamental. This structure allows you to access different data groups without needing to know the specific underlying source.

    • Market(): For market data like stock prices (OHLCV) and indices.
    • Reference(): For reference data like company profiles.
    • Fundamental(): For fundamental data like financial statements.
    from vnstock import Market, Reference, Fundamental
    
    market = Market()
    ref = Reference()
    fa = Fundamental()
    
    # Get historical stock price data (OHLCV)
    df_history = market.equity.ohlcv(symbol='VNM', start='2024-01-01', end='2024-05-01')
    
    # Get general company profile information
    df_profile = ref.company.info(symbol='FPT')
    
    # Get financial statements (Balance Sheet) by period
    df_balance = fa.equity.balance_sheet(symbol='TCB', period='year')
    from vnstock import Market, Reference, Fundamental
    
    market = Market()
    ref = Reference()
    fa = Fundamental()
    
    # Lấy dữ liệu lịch sử giá cổ phiếu (OHLCV)
    df_history = market.equity.ohlcv(symbol='VNM', start='2024-01-01', end='2024-05-01')
    
    # Lấy thông tin hồ sơ doanh nghiệp tổng quan
    df_profile = ref.company.info(symbol='FPT')
    
    # Lấy báo cáo tài chính (Bảng cân đối kế toán) theo năm
    df_balance = fa.equity.balance_sheet(symbol='TCB', period='year')
  4. Enable Debug Mode for ProxyManager

    main

    To troubleshoot proxy fetching or testing, enable detailed logging using the standard logging module. This will show debug logs during operations like fetch_proxies().

    import logging
    
    logging.basicConfig(level=logging.DEBUG)
    
    manager = ProxyManager()
    proxies = manager.fetch_proxies(limit=5)  # Will show debug logs
  5. Quick Start with Vnstock v4+ Unified UI

    main

    Vnstock v4+ uses a Unified UI pattern. You initialize data domains (Market, Reference, Fundamental) and then access specific data through their hierarchical structure. This allows you to fetch data without needing to manually manage underlying data sources.

    from vnstock import Market, Reference, Fundamental
    
    # Initialize data domains
    market = Market()
    ref = Reference()
    fa = Fundamental()
    
    # 1. Fetch historical stock prices (OHLCV)
    df_history = market.equity.ohlcv(symbol='VNM', start='2024-01-01', end='2024-05-01')
    
    # 2. Fetch general company profile
    df_profile = ref.company.info(symbol='FPT')
    
    # 3. Fetch financial data
    df_balance = fa.equity.balance_sheet(symbol='TCB', period='year')
  6. Persist proxies to and from JSON

    main

    You can save a list of Proxy objects to a JSON file and reload them later to avoid repeated fetching and rate limiting.

    import json
    
    def save_proxies(proxies, filename='proxies.json'):
        data = [
            {
                'protocol': p.protocol,
                'ip': p.ip,
                'port': p.port,
                'country': p.country,
                'speed': p.speed
            }
            for p in proxies
        ]
        with open(filename, 'w') as f:
            json.dump(data, f)
    
    def load_proxies(filename='proxies.json'):
        from vnstock.core.utils.proxy_manager import Proxy
    
        with open(filename) as f:
            data = json.load(f)
    
        return [Proxy(**item) for item in data]
    
    # Usage
    proxies = manager.fetch_proxies(limit=10)
    save_proxies(proxies)
    
    # Later...
    proxies = load_proxies()
    working, _ = manager.test_proxies(proxies)
  7. Filter and sort proxies

    main

    Once you have a list of Proxy objects, you can filter them using their attributes: protocol, speed (in ms), and country.

    # Get only HTTP proxies
    http_only = [p for p in proxies if p.protocol == 'http']
    
    # Get only proxies under 100ms
    fast_proxies = [p for p in proxies if p.speed < 100]
    
    # Get specific country
    vietnam_proxies = [p for p in proxies if 'Vietnam' in p.country]
  8. Use the Market Layer to retrieve asset data

    main

    The Market class is the entry point for the Unified UI, allowing you to access different asset classes through specific methods.

    Initialize the market object as follows:

    from vnstock import Market
    
    mkt = Market()

    Available asset layers include:

    • mkt.equity(symbol): Stocks
    • mkt.index(symbol): Market Indices
    • mkt.futures(symbol): Futures contracts
    • mkt.warrant(symbol): Warrants
    • mkt.etf(symbol): ETFs
    • mkt.fund(symbol): Mutual Funds
    • mkt.crypto(symbol): Cryptocurrency (via Binance)
    • mkt.forex(symbol): Forex and Gold
  9. How the Fundamental layer works and its calling conventions

    main

    The Fundamental module in vnstock provides access to financial statements (Income Statement, Balance Sheet, Cash Flow) and Financial Ratios for equities.

    To use it, initialize the layer with fun = Fundamental().

    The module supports two flexible calling conventions (Proxy chaining):

    1. Object-oriented style: fun.equity("SYMBOL").method() — Best for chaining operations on a specific ticker.
    2. Utility function style: fun.equity.method("SYMBOL") — A functional approach to calling methods.

    Both styles yield the same results.

  10. How the Unified UI (Wrapper) works with FMP

    main

    vnstock uses a Unified UI (Standard Wrapper) pattern. This allows you to switch between different data sources (like VCI, TCBS, FMP, etc.) using the same interface by simply changing the source parameter.

    There are two ways to access FMP data:

    1. Recommended (Standard Wrapper): Import Quote from vnstock and specify source='fmp'. This is the most flexible method for switching sources.
    2. Direct Module Access: Import directly from vnstock.connector.fmp. This method does not require the source parameter.

    Using the standard wrapper makes it easy to swap data providers without changing your core logic.

    # Cách mới: Wrapper tiêu chuẩn (Khuyến nghị)
    from vnstock import Quote
    
    # Khởi tạo với source='fmp'
    quote_fmp = Quote(symbol='AAPL', source='fmp')
    
    # Nạp từ wrapper chính của thư viện
    from vnstock import Quote
    q = Quote(symbol='AAPL', source='fmp')
    
    # Nạp từ module con
    from vnstock.connector.fmp import Quote as FMPQuote
    q = FMPQuote(symbol='AAPL')