API Reference¶
This page contains the auto-generated API reference for aynse.
NSE Module¶
The main module for fetching NSE data.
Historical Data¶
aynse.nse.history.stock_csv
¶
aynse.nse.history.derivatives_df
¶
derivatives_df(symbol, from_date, to_date, expiry_date, instrument_type, strike_price=None, option_type=None)
aynse.nse.history.derivatives_csv
¶
derivatives_csv(symbol, from_date, to_date, expiry_date, instrument_type, strike_price=None, option_type=None, output='', show_progress=False)
aynse.nse.history.set_stock_history_backend
¶
Set the stock history backend globally for stock_raw/stock_df/stock_csv.
Backends: - auto: try NSE historical API, then fallback to bhavcopy reconstruction - nse: use NSE historical API only - bhavcopy: use bhavcopy reconstruction only - custom: use user-registered provider only
aynse.nse.history.get_stock_history_backend
¶
Return currently configured global stock history backend.
aynse.nse.history.register_stock_history_provider
¶
Register a custom stock history provider used when backend is 'custom'.
The provider signature must be
provider(symbol: str, from_date: date, to_date: date, series: str) -> list[dict]
Archives¶
aynse.nse.archives.index_constituent_raw
module-attribute
¶
aynse.nse.archives.index_constituent_save
module-attribute
¶
aynse.nse.archives.index_constituent_save_all
module-attribute
¶
aynse.nse.archives.expiry_dates
¶
expiry_dates(dt: date, instrument_type: str = '', symbol: str = '', contracts: int = 0, months_ahead: int = 6) -> list
Algorithmically calculate expiry dates based on NSE rules.
| PARAMETER | DESCRIPTION |
|---|---|
dt
|
Reference date for calculation
TYPE:
|
instrument_type
|
Type of derivative instrument (e.g., "FUTIDX", "OPTIDX", "FUTSTK", "OPTSTK")
TYPE:
|
symbol
|
Symbol name (used to determine contract cycle)
TYPE:
|
contracts
|
Minimum open interest filter (deprecated in algorithmic approach)
TYPE:
|
months_ahead
|
Number of months ahead to calculate expiries for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
List of expiry dates |
Live Data¶
aynse.nse.live.NSELive
¶
Initialize NSELive with centralized HTTP client
chart_data
¶
Fetch intraday/period graph data.
NSE moved live chart data to NextApi:
- Equities: /api/NextApi/apiClient/GetQuoteApi?functionName=getSymbolChartData
symbol must be days parameter (e.g., 1D, 5D, 3M)
- Indices: /api/NextApi/apiClient?functionName=getGraphChart
uses type and flag (e.g., 1D, 5D, 6M)
We normalize responses so callers still receive a dict with grapthData.
corporate_announcements
¶
This function returns the corporate annoucements (https://www.nseindia.com/companies-listing/corporate-filings-announcements)
bulk_equities_option_chain
¶
Fetch option chains for multiple equity symbols concurrently.
| PARAMETER | DESCRIPTION |
|---|---|
symbols
|
List of equity symbols
TYPE:
|
max_workers
|
Maximum number of concurrent requests
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary with symbol as key and option chain data as value
TYPE:
|
get_options_around_date
¶
Get option chain data and analyze it in context of a target date (like earnings).
| PARAMETER | DESCRIPTION |
|---|---|
symbol
|
Equity symbol
TYPE:
|
target_date
|
Target date (e.g., earnings date)
TYPE:
|
days_before
|
Days before target date to consider
TYPE:
|
days_after
|
Days after target date to consider
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Analysis of options around the target date
TYPE:
|
analyze_earnings_options
¶
Analyze option chains for multiple stocks around their earnings dates.
| PARAMETER | DESCRIPTION |
|---|---|
symbols_and_dates
|
List of tuples (symbol, earnings_date)
TYPE:
|
max_workers
|
Maximum concurrent requests
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Analysis results for each symbol
TYPE:
|
Holidays Module¶
aynse.holidays
¶
Trading holidays for NSE (National Stock Exchange of India).
This module provides a comprehensive list of trading holidays and utilities for checking if a given date is a trading day.
The holiday list is based on the Zipline calendar library and is updated with official NSE holiday announcements.
holidays
¶
Get list of NSE trading holidays.
| PARAMETER | DESCRIPTION |
|---|---|
year
|
Filter by year (optional). If None, returns all holidays.
TYPE:
|
month
|
Filter by month (optional, requires year to be set).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[date]
|
List of holiday dates, sorted in chronological order. |
Examples:
is_holiday
¶
Check if a date is an NSE trading holiday.
| PARAMETER | DESCRIPTION |
|---|---|
dt
|
Date to check
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the date is a holiday, False otherwise |
Example
from datetime import date is_holiday(date(2024, 1, 26)) # Republic Day True
is_trading_day
¶
Check if a date is a trading day.
A trading day is a weekday (Monday-Friday) that is not a holiday.
| PARAMETER | DESCRIPTION |
|---|---|
dt
|
Date to check
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the date is a trading day, False otherwise |
Example
from datetime import date is_trading_day(date(2024, 1, 15)) # Monday, not a holiday True is_trading_day(date(2024, 1, 13)) # Saturday False
get_trading_days
¶
Get all trading days in a date range.
| PARAMETER | DESCRIPTION |
|---|---|
from_date
|
Start date (inclusive)
TYPE:
|
to_date
|
End date (inclusive)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[date]
|
List of trading days in the range, sorted chronologically |
Example
from datetime import date trading_days = get_trading_days(date(2024, 1, 1), date(2024, 1, 31))
count_trading_days
¶
Count the number of trading days in a date range.
| PARAMETER | DESCRIPTION |
|---|---|
from_date
|
Start date (inclusive)
TYPE:
|
to_date
|
End date (inclusive)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of trading days in the range |
RBI Module¶
aynse.rbi.RBI
¶
Client for fetching RBI (Reserve Bank of India) data.
Provides access to policy rate archives and other monetary policy information from the RBI website.
Example
rbi = RBI() rates = rbi.policy_rate_archive(n=10) print(rates[0])
Initialize RBI client with a requests session.
current_rates
¶
Get current RBI policy rates.
.. deprecated::
This function is broken due to website changes.
Use policy_rate_archive() instead.
| RAISES | DESCRIPTION |
|---|---|
DeprecationWarning
|
Always raised as this method is deprecated |
policy_rate_archive
¶
Fetch historical policy rates from RBI website.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of past rate records to fetch (default: 10)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Dict[str, Any]]
|
List of dictionaries containing policy rate data. |
List[Dict[str, Any]]
|
Keys are normalized to lowercase with underscores. |
Example
rbi = RBI() rates = rbi.policy_rate_archive(n=5) for rate in rates: ... print(rate.get('date'), rate.get('repo_rate'))
aynse.rbi.policy_rate_archive
¶
Fetch historical policy rates from RBI website.
Scrapes the RBI policy rate archive page to extract historical policy rate data including repo rate, reverse repo rate, etc.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of past rate records to fetch (default: 10). Higher values will fetch more historical data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Dict[str, Any]]
|
List of dictionaries containing policy rate data. |
List[Dict[str, Any]]
|
Each dictionary represents one rate announcement. |
List[Dict[str, Any]]
|
Column names are normalized to lowercase with underscores. |
| RAISES | DESCRIPTION |
|---|---|
RequestException
|
If the HTTP request fails |
ValueError
|
If no data table is found on the page |
Example
rates = policy_rate_archive(n=5) for rate in rates: ... print(f"Date: {rate.get('date')}, Repo: {rate.get('repo_rate')}")
HTTP Client¶
The library includes resilient HTTP clients with retry logic, rate limiting, and circuit breakers.
NSEHttpClient¶
from aynse.nse.http_client import NSEHttpClient
client = NSEHttpClient(
base_url="https://www.nseindia.com",
timeout=15.0,
max_connections=20,
rate_limit_per_sec=10
)
# Make requests
response = client.get("/api/marketStatus")
data = client.get_json("/api/marketStatus")
Connection Pool¶
from aynse.nse.connection_pool import get_connection_pool
pool = get_connection_pool()
client = pool.get_client("https://www.nseindia.com")
# The pool manages client lifecycle and reuse
data = client.get_json("/api/marketStatus")
# Get pool statistics
stats = pool.get_pool_stats()
print(f"Active clients: {stats['sync_clients']}")
Request Batching¶
aynse.nse.request_batcher.RequestBatcher
¶
RequestBatcher(max_batch_size: int = 10, max_concurrent_batches: int = 3, timeout: float = 30.0, strategy: BatchStrategy = ADAPTIVE)
Efficient request batching system for NSE API calls.
Supports both synchronous and asynchronous batching with different strategies.
Initialize the request batcher.
| PARAMETER | DESCRIPTION |
|---|---|
max_batch_size
|
Maximum requests per batch
TYPE:
|
max_concurrent_batches
|
Maximum concurrent batch processors
TYPE:
|
timeout
|
Request timeout in seconds
TYPE:
|
strategy
|
Batching strategy to use
TYPE:
|
abatch_requests
async
¶
abatch_requests(requests: List[Dict[str, Any]], request_coro_func: Callable[..., Future[Any]], max_concurrency: Optional[int] = None, **kwargs: Any) -> List[BatchResult]
Async batch processing with bounded concurrency.
| PARAMETER | DESCRIPTION |
|---|---|
requests
|
List of request parameter dicts
TYPE:
|
request_coro_func
|
Async function to call per request
TYPE:
|
max_concurrency
|
Optional concurrency cap (defaults to max_concurrent_batches * max_batch_size)
TYPE:
|
**kwargs
|
Extra kwargs for request function
TYPE:
|
batch_requests
¶
batch_requests(requests: List[Dict[str, Any]], request_func: Callable[..., Any], **kwargs: Any) -> List[BatchResult]
Process multiple requests in batches.
| PARAMETER | DESCRIPTION |
|---|---|
requests
|
List of request parameters
TYPE:
|
request_func
|
Function to process individual requests
TYPE:
|
**kwargs
|
Additional arguments for request_func
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[BatchResult]
|
List of BatchResult objects |
aynse.nse.request_batcher.BatchStrategy
¶
Bases: Enum
Different strategies for batching requests
Streaming Processor¶
aynse.nse.streaming_processor.StreamingProcessor
¶
StreamingProcessor(config: Optional[StreamConfig] = None)
Efficient streaming processor for large NSE datasets.
Processes data in chunks to minimize memory usage and handle large files that wouldn't fit in memory.
Initialize streaming processor with configuration
process_csv_file
¶
process_csv_file(file_path: str, processor_func: Callable[[List[Dict[str, Any]]], Any], skip_header: bool = True) -> Any
Process a CSV file in streaming chunks.
| PARAMETER | DESCRIPTION |
|---|---|
file_path
|
Path to CSV file
TYPE:
|
processor_func
|
Function to process each chunk of data
TYPE:
|
skip_header
|
Whether to skip the first row (header)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Result of processing all chunks |
process_csv_string
¶
process_csv_string(csv_data: str, processor_func: Callable[[List[Dict[str, Any]]], Any], skip_header: bool = True) -> Any
Process CSV data from string in streaming chunks.
| PARAMETER | DESCRIPTION |
|---|---|
csv_data
|
CSV data as string
TYPE:
|
processor_func
|
Function to process each chunk
TYPE:
|
skip_header
|
Whether to skip the first row
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Result of processing all chunks |
process_json_file
¶
Process a JSON file in streaming chunks.
| PARAMETER | DESCRIPTION |
|---|---|
file_path
|
Path to JSON file (assumed to be array of objects)
TYPE:
|
processor_func
|
Function to process each chunk
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Result of processing all chunks |
process_zip_file
¶
process_zip_file(zip_path: str, processor_func: Callable[[List[Dict[str, Any]]], Any], csv_filename: Optional[str] = None) -> Any
Process CSV data from within a ZIP file in streaming chunks.
| PARAMETER | DESCRIPTION |
|---|---|
zip_path
|
Path to ZIP file
TYPE:
|
processor_func
|
Function to process each chunk
TYPE:
|
csv_filename
|
Specific CSV file within ZIP (if None, uses first CSV found)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
Result of processing all chunks |
aynse.nse.streaming_processor.StreamConfig
dataclass
¶
StreamConfig(chunk_size: int = 1000, max_memory_mb: int = 100, buffer_size: int = 8192, encoding: str = 'utf-8')
Configuration for streaming data processing
Utilities¶
aynse.util.break_dates
¶
break_dates(from_date: date, to_date: date, max_days_per_chunk: int = 31) -> List[Tuple[date, date]]
Break a date range into monthly chunks for efficient API calls.
The NSE API typically limits requests to one month at a time, so this function splits larger date ranges into monthly chunks.
| PARAMETER | DESCRIPTION |
|---|---|
from_date
|
Start date of the range
TYPE:
|
to_date
|
End date of the range
TYPE:
|
max_days_per_chunk
|
Maximum days per chunk (default: 31)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Tuple[date, date]]
|
List of (start_date, end_date) tuples for each chunk |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If from_date is after to_date |
Example
from datetime import date break_dates(date(2024, 1, 15), date(2024, 3, 20)) [(date(2024, 1, 15), date(2024, 1, 31)), (date(2024, 2, 1), date(2024, 2, 29)), (date(2024, 3, 1), date(2024, 3, 20))]
aynse.util.cached
¶
Decorator for caching function results to disk.
Results are stored as gzip-compressed pickle files in a user-specific cache directory. The cache key is generated from the function arguments.
| PARAMETER | DESCRIPTION |
|---|---|
app_name
|
Name of the application (used for cache directory)
TYPE:
|
max_age_seconds
|
Optional TTL for cache entries. If set, expired cache files are ignored and rebuilt.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[F], F]
|
Decorator function |
Environment Variables
J_CACHE_DIR: Override default cache directory
Example
@cached("myapp") def expensive_function(symbol, date): # ... expensive API call ... return data
aynse.util.live_cache
¶
Decorator for time-based caching of live data functions.
Caches the result of a function for a configurable timeout period. This is useful for live market data where we want to avoid hitting the API too frequently but still get reasonably fresh data.
The decorated class must have a time_out attribute specifying
the cache duration in seconds.
| PARAMETER | DESCRIPTION |
|---|---|
func
|
Method to cache (must be an instance method)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
F
|
Wrapped method with time-based caching |
Example
class LiveData: time_out = 5 # Cache for 5 seconds
@live_cache
def get_quote(self, symbol):
# ... expensive API call ...
return quote
aynse.util.is_trading_day
¶
Check if a given date is a trading day.
A trading day is a weekday (Monday-Friday) that is not a holiday.
| PARAMETER | DESCRIPTION |
|---|---|
dt
|
Date to check
TYPE:
|
holidays_list
|
Optional list of holiday dates. If None, uses the holidays from the holidays module.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the date is a trading day, False otherwise |