Skip to main content

A professional Python library for Indian stock market data and analysis

Project description

Indian Stock Market Library

A professional Python library for accessing and analyzing Indian stock market data from NSE (National Stock Exchange) with a focus on technical analysis, real-time streaming, and reliable data fetching.

Features

  • Clean Architecture: Modern, extensible design with proper separation of concerns
  • NSE Data Access: Comprehensive NSE market data including stocks, indices, ETFs, SGBs
  • WebSocket-Style Streaming: Real-time data streaming with historical backfill
  • Technical Analysis Ready: OHLC data, second-wise data, and market indicators
  • Robust Error Handling: Graceful handling of API failures and network issues
  • Rate Limiting: Built-in rate limiting to respect API limits
  • Professional Documentation: Well-documented code with type hints

Installation

pip install indian-stock-market

Quick Start

from indian_stock_market import NSE

# Initialize NSE client
nse = NSE()

# Get stock trade information
reliance_data = nse.get_trade_info("RELIANCE")
print(reliance_data)

# Get NIFTY 50 constituents
nifty_stocks = nse.get_equities_data_from_index("NIFTY 50")
print(nifty_stocks)

# Get all indices data
all_indices = nse.get_all_indices()
print(all_indices)

# Get OHLC data
ohlc_data = nse.get_ohlc_data("RELIANCE", timeframe="5Min", is_index=False)
print(ohlc_data)

WebSocket-Style Real-Time Streaming (NEW in v0.2.0)

Stream real-time market data with automatic historical backfill:

from indian_stock_market import NSE
import time

nse = NSE()

def on_update(candle, is_historical):
    """
    Callback receives:
    - candle: Dict with OHLC data
    - is_historical: True for initial candles, False for live ticks
    """
    if is_historical:
        print(f"📊 Historical: {candle['time']} @ ₹{candle['close']:.2f}")
    else:
        print(f"🔴 Live: {candle['time']} @ ₹{candle['close']:.2f}")

# Subscribe to real-time updates
subscription = nse.subscribe_symbol(
    symbol="RELIANCE",
    callback=on_update,
    interval=60  # Update every 60 seconds
)

# Let it run for 5 minutes
time.sleep(300)
subscription['stop']()

Key Features:

  • First call returns all candles since market open (9:15 AM IST)
  • Subsequent calls stream live tick data
  • Perfect for building trading bots and indicators
  • Automatic timezone handling (IST)

See WEBSOCKET_API.md for complete documentation.

Available Methods

Real-Time Streaming (NEW)

  • subscribe_symbol(symbol, callback, interval) - Subscribe to real-time updates with historical backfill
  • subscribe_multiple(symbols, callback, interval) - Subscribe to multiple symbols
  • stream_symbol(symbol, duration, callback) - Blocking stream for simpler use cases

Market Data

  • get_trade_info(ticker) - Get comprehensive trade information
  • get_equities_data_from_index(index) - Get stocks from specific index
  • get_all_indices() - Get all NSE indices data
  • get_ohlc_data(symbol, timeframe) - Get OHLC data
  • get_india_vix(from_date, to_date) - Get India VIX historical data

Specialized Data

  • get_sme_stocks() - Get SME stocks data
  • get_sgb_data() - Get Sovereign Gold Bonds data
  • get_all_etf() - Get all ETF data
  • get_block_deals() - Get today's block deals
  • get_corporate_disclosures(ticker) - Get corporate announcements

Market Analysis

  • get_top_gainers_losers(index) - Get top gainers and losers
  • get_market_reports() - Get important market reports
  • search(query) - Search for stocks/indices

Utilities

  • get_market_status_and_current_val(index) - Check market status
  • get_last_traded_date() - Get last trading date

Examples

Get Stock Information

# Single stock
stock_data = nse.get_trade_info("TCS")

# Multiple stocks
stocks_data = nse.get_trade_info(["RELIANCE", "TCS", "INFY"])

Get Index Constituents

# NIFTY 50 stocks
nifty50 = nse.get_equities_data_from_index("NIFTY 50")

# Bank NIFTY stocks
bank_nifty = nse.get_equities_data_from_index("NIFTY BANK")

# F&O securities
fno_stocks = nse.get_equities_data_from_index("SECURITIES IN F&O")

Technical Analysis Data

# Get OHLC data for different timeframes
daily_data = nse.get_ohlc_data("RELIANCE", "1Day", is_index=False)
minute_data = nse.get_ohlc_data("RELIANCE", "5Min", is_index=False)
intraday_data = nse.get_ohlc_data("RELIANCE", "1Min", is_index=False)

# Get current market data
market_status = nse.get_market_status()

# Get India VIX data
vix_data = nse.get_india_vix()  # Default: previous day to today
vix_historical = nse.get_india_vix('01-02-2026', '04-02-2026')  # Custom range

Market Analysis

# Get top gainers and losers
gainers_losers = nse.get_top_gainers_losers("NIFTY 50")
print("Top Gainers:")
print(gainers_losers['gainers'])
print("Top Losers:")
print(gainers_losers['losers'])

# Search for stocks
search_results = nse.search("reliance")

Error Handling

The library includes comprehensive error handling:

try:
    data = nse.get_trade_info("INVALID_SYMBOL")
except Exception as e:
    print(f"Error: {e}")

Rate Limiting

Built-in rate limiting ensures compliance with NSE API limits:

  • Minimum 500ms between requests
  • Automatic retry with exponential backoff
  • Graceful handling of rate limit responses

Requirements

  • Python 3.9+
  • polars >= 0.20.0
  • httpx >= 0.25.0
  • pydantic >= 2.5.0

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Disclaimer

This library is for educational and research purposes only. Please ensure compliance with NSE's terms of service and applicable regulations when using this library for commercial purposes.

Support

For issues and questions, please open an issue on GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

indian_stock_market-0.6.0.tar.gz (55.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

indian_stock_market-0.6.0-py3-none-any.whl (68.0 kB view details)

Uploaded Python 3

File details

Details for the file indian_stock_market-0.6.0.tar.gz.

File metadata

  • Download URL: indian_stock_market-0.6.0.tar.gz
  • Upload date:
  • Size: 55.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.19

File hashes

Hashes for indian_stock_market-0.6.0.tar.gz
Algorithm Hash digest
SHA256 574cb8a29d68c2341134aeb250e0bcac761ea73463d0834d979f1475909ce24c
MD5 f003f854cb90303966113f063a6ec230
BLAKE2b-256 0f6052f27c5ae79054cf75deed2017fdc1afbc1edd17983b93bd30f5bfccf573

See more details on using hashes here.

File details

Details for the file indian_stock_market-0.6.0-py3-none-any.whl.

File metadata

File hashes

Hashes for indian_stock_market-0.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d9fd426a88f83be05247bf6f2e62d47702ba9e587c4275c132292bcad61aef9e
MD5 242badb0ddc66f05623f73e45c1e9a01
BLAKE2b-256 dff242e0d48b2fc4fa1cb4a31e8ce0886887c27fc60e63c1d9a8f6a4b23cfe4d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page