indian-stock-market 0.6.0
A professional Python library for Indian stock market data and analysis
Requires Python: >=3.10
Keywords: bse, finance, india, market, nse, stock, technical-analysis, trading

# 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

```bash
pip install indian-stock-market
```

## Quick Start

```python
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:

```python
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](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
```python
# Single stock
stock_data = nse.get_trade_info("TCS")

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

### Get Index Constituents
```python
# 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
```python
# 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
```python
# 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:

```python
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.