CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-vnstock

A beginner-friendly yet powerful Python toolkit for financial analysis and automation — built to make modern investing accessible to everyone

Overview
Eval results
Files

quote-data.mddocs/

Quote Data Management

The Quote class provides access to historical and real-time price data including OHLC history, intraday trading data, and market depth information. It supports multiple Vietnamese and international data sources with automatic retry logic and caching.

Capabilities

Quote Class

Adapter for historical and intraday quote data with dynamic method dispatch based on the selected data source. Uses automatic parameter filtering and retry logic for reliable data access.

class Quote:
    """
    Quote data adapter supporting multiple data sources.
    
    Supported sources: VCI, TCBS, MSN
    """
    
    def __init__(self, source: str = "vci", symbol: str = "", random_agent: bool = False, show_log: bool = False):
        """
        Initialize Quote data adapter.
        
        Args:
            source (str): Data source ("vci", "tcbs", "msn"), defaults to "vci"
            symbol (str): Default symbol for operations, defaults to ""
            random_agent (bool): Use random user agent, defaults to False
            show_log (bool): Enable logging, defaults to False
        """

Historical Price Data

Retrieve historical OHLC (Open, High, Low, Close) price data for stocks, indices, forex, and cryptocurrencies with customizable date ranges and intervals.

def history(self, *args, **kwargs) -> pd.DataFrame:
    """
    Load historical OHLC price data.
    
    Common parameters (vary by source):
        symbol (str): Security symbol
        start (str): Start date in "YYYY-MM-DD" format
        end (str): End date in "YYYY-MM-DD" format  
        interval (str): Data interval ("1D", "1W", "1M")
        
    Returns:
        pd.DataFrame: Historical price data with columns:
            - time/date: Timestamp
            - open: Opening price
            - high: High price
            - low: Low price
            - close: Closing price
            - volume: Trading volume
    """

Usage Examples

from vnstock import Quote

# Initialize Quote adapter
quote = Quote(source="vci", symbol="TCB")

# Get 1 year of daily data
daily_data = quote.history(
    symbol="TCB",
    start="2023-01-01", 
    end="2023-12-31",
    interval="1D"
)

# Get weekly data
weekly_data = quote.history(
    symbol="VCB",
    start="2023-01-01",
    end="2023-12-31", 
    interval="1W"
)

# Using TCBS source
tcbs_quote = Quote(source="tcbs")
tcbs_data = tcbs_quote.history(
    symbol="HPG",
    start="2023-06-01",
    end="2023-12-31"
)

Intraday Trading Data

Access intraday trading data including tick-by-tick transactions, minute-level price movements, and detailed trading activity.

def intraday(self, *args, **kwargs) -> pd.DataFrame:
    """
    Load intraday trading data with high-frequency price and volume information.
    
    Common parameters (vary by source):
        symbol (str): Security symbol
        date (str): Trading date in "YYYY-MM-DD" format
        interval (str): Intraday interval ("1m", "5m", "15m", "30m", "1h")
        
    Returns:
        pd.DataFrame: Intraday trading data with columns:
            - time: Timestamp
            - open: Opening price
            - high: High price
            - low: Low price
            - close: Closing price
            - volume: Trading volume
            - value: Trading value
    """

Usage Examples

# Get intraday minute data for today
intraday_data = quote.intraday(
    symbol="TCB",
    date="2023-12-15",
    interval="1m"
)

# Get 5-minute intervals
intraday_5m = quote.intraday(
    symbol="VCB", 
    date="2023-12-15",
    interval="5m"
)

# Hourly intraday data
hourly_data = quote.intraday(
    symbol="HPG",
    date="2023-12-15",
    interval="1h"
)

Market Depth Data

Retrieve price depth information including order book data, bid/ask levels, and market liquidity indicators.

def price_depth(self, *args, **kwargs) -> pd.DataFrame:
    """
    Load price depth (order book) data showing bid/ask levels and quantities.
    
    Common parameters (vary by source):
        symbol (str): Security symbol  
        levels (int): Number of price levels to retrieve
        
    Returns:
        pd.DataFrame: Order book data with columns:
            - bid_price_1, bid_price_2, ...: Bid prices by level
            - bid_volume_1, bid_volume_2, ...: Bid quantities by level
            - ask_price_1, ask_price_2, ...: Ask prices by level  
            - ask_volume_1, ask_volume_2, ...: Ask quantities by level
            - timestamp: Data timestamp
    """

Usage Examples

# Get order book for TCB stock
order_book = quote.price_depth(symbol="TCB", levels=5)

# Get market depth with more levels
deep_book = quote.price_depth(symbol="VCB", levels=10)

# Current bid/ask spread analysis
spread_data = quote.price_depth(symbol="HPG")

Data Source Specifics

VCI (Vietnam Capital Securities)

  • Coverage: Vietnamese stocks, ETFs, covered warrants
  • Historical Data: Up to 10+ years of daily data
  • Intraday Data: Real-time tick data and minute intervals
  • Market Depth: 5-10 levels of order book data
  • Update Frequency: Real-time during market hours

VCI-Specific Parameters

# VCI history parameters
history(
    symbol="TCB",
    start="2023-01-01",
    end="2023-12-31",
    resolution="1D",  # VCI uses "resolution" instead of "interval"
    type="stock"      # "stock", "index", "warrant"
)

# VCI intraday parameters  
intraday(
    symbol="TCB",
    fromDate="2023-12-15 09:00:00",
    toDate="2023-12-15 15:00:00",
    resolution="1"  # Minutes
)

TCBS (Techcombank Securities)

  • Coverage: Vietnamese stocks, indices, derivatives
  • Historical Data: Comprehensive historical database
  • Intraday Data: Minute-level and tick data
  • Market Depth: Real-time order book
  • Update Frequency: Real-time during market hours

TCBS-Specific Parameters

# TCBS history parameters
history(
    ticker="HPG",
    type="stock",
    start="2023-01-01",
    end="2023-12-31",
    period="D"  # Daily period
)

# TCBS intraday
intraday(
    ticker="VCB",
    date="2023-12-15",
    size=1000  # Number of records
)

MSN (Microsoft Network)

  • Coverage: Global stocks, forex, crypto, indices
  • Historical Data: Long-term historical data for global markets
  • Intraday Data: International market data
  • Market Depth: Limited order book for major markets
  • Update Frequency: Real-time for major markets

MSN-Specific Parameters

# MSN forex data
history(
    symbol="USDVND",
    start="2023-01-01",
    end="2023-12-31",
    interval="1D"
)

# MSN crypto data
history(
    symbol="BTC", 
    range="1Y",  # MSN supports range parameter
    interval="1D"
)

Error Handling

The Quote class includes built-in error handling and retry logic:

  • Network Errors: Automatic retry with exponential backoff
  • Rate Limiting: Handles API rate limits with appropriate delays
  • Data Validation: Validates date ranges and symbol formats
  • Source Fallback: Can switch between data sources if primary fails

Common Error Scenarios

try:
    data = quote.history(symbol="INVALID", start="2023-01-01", end="2023-12-31")
except ValueError as e:
    print(f"Invalid symbol or date range: {e}")
except ConnectionError as e:
    print(f"Network error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

Performance Considerations

  • Caching: Recent data requests are cached to improve performance
  • Batch Requests: Use date ranges instead of multiple single-day requests
  • Data Sources: VCI and TCBS are optimized for Vietnamese markets
  • Rate Limits: Respect API rate limits to avoid throttling
  • Memory Usage: Large date ranges may consume significant memory

Install with Tessl CLI

npx tessl i tessl/pypi-vnstock

docs

company-info.md

data-visualization.md

financial-statements.md

index.md

main-client.md

market-listings.md

mutual-funds.md

quote-data.md

stock-screening.md

trading-analytics.md

tile.json