nepse_client Package

NEPSE Client - A comprehensive Python library for Nepal Stock Exchange API.

This package provides both synchronous and asynchronous clients for accessing NEPSE market data, company information, trading details, and more.

Example: Synchronous usage:

from nepse_client import NepseClient

client = NepseClient()
market_status = client.getMarketStatus()
companies = client.getCompanyList()

Asynchronous usage:

import asyncio
from nepse_client import AsyncNepseClient

async def main():
   client = AsyncNepseClient()
   market_status = await client.getMarketStatus()
   companies = await client.getCompanyList()

asyncio.run(main())
class nepse_client.NepseClient[source]

Bases: _NepseBase

Synchronous client for NEPSE API.

This client provides blocking methods to access Nepal Stock Exchange data including market status, company information, trading data, and more.

Parameters:
  • logger (Optional[Logger]) – Optional custom logger instance

  • mask_request_data (bool) – Whether to mask sensitive data in logs (default: True)

  • timeout (float) – Request timeout in seconds (default: 100.0)

Example

Basic usage:

from nepse_client import NepseClient

client = NepseClient()

# Get market status
status = client.getMarketStatus()
print(f"Market is {status['isOpen']}")

# Get company details
nabil = client.getCompanyDetails("NABIL")
print(f"NABIL LTP: {nabil['lastTradedPrice']}")

Note

The client automatically manages authentication tokens and handles token expiration transparently.

__enter__()[source]

Context manager entry.

__exit__(exc_type, exc_val, exc_tb)[source]

Context manager exit - cleanup resources.

__init__(logger=None, mask_request_data=True, timeout=100.0)[source]

Initialize synchronous NEPSE client.

Parameters:
  • logger (Logger | None)

  • mask_request_data (bool)

  • timeout (float)

close()[source]

Close HTTP client and cleanup resources.

Return type:

None

getAuthorizationHeaders()[source]

Get headers with authorization token.

Return type:

dict[str, str]

Returns:

Dictionary of HTTP headers

getCompanyAGM(company_id=None)[source]

Get Annual General Meeting (AGM) information for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing AGM details for the company.

Each dictionary might include keys like ‘meetingDate’, ‘agenda’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with a ‘fullFilePath’ key for document access.

Return type:

list

getCompanyDetails(symbol)[source]

Get detailed information for a specific company.

Parameters:

symbol (str) – Company stock symbol (e.g., “NABIL”)

Return type:

dict[str, Any]

Returns:

Dictionary with company details

Raises:

KeyError – If symbol not found

getCompanyDividend(company_id=None)[source]

Get dividend information for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing dividend details for the company.

Each dictionary might include keys like ‘dividendType’, ‘rate’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with a ‘fullFilePath’ key for document access.

Return type:

list

getCompanyFinancialDetails(company_id=None)[source]

Get financial details for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing financial details for the company.

Each dictionary might include keys like ‘period’, ‘financialMetrics’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with ‘fullFilePath’ and ‘fullEncryptedPath’ keys for

Return type:

list

getCompanyIDKeyMap(force_update=False)[source]

Get mapping of company symbols to IDs.

Parameters:

force_update (bool) – Force refresh of cached data

Return type:

dict[str, int]

Returns:

Dictionary mapping symbol to company ID

getCompanyList()[source]

Get list of all listed companies.

Return type:

list[dict[str, Any]]

Returns:

List of company dictionaries

Note

Results are cached internally. Subsequent calls return cached data unless cache is cleared.

getCompanyMarketDepth(company_id=None)[source]

Get market depth information for a specific company.

Market depth typically includes buy and sell orders at various price levels.

Parameters:

company_id (str, optional) – The unique identifier (symbol or code) for the company/security. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list containing market depth data for the company.

The structure of the data depends on the API response, but it usually includes buy/sell orders with prices and volumes. Returns an empty list if no data is found or an error occurs during the API request.

Return type:

list

getCompanyNewsList(page=0, page_size=100, is_strip_tags=True)[source]

Get list of company news.

Return type:

dict[str, Any]

Parameters:
  • page (int)

  • page_size (int)

  • is_strip_tags (bool)

getCompanyPriceVolumeHistory(symbol, start_date=None, end_date=None)[source]

Get price and volume history for a company.

Parameters:
  • symbol (str) – Company symbol

  • start_date (Union[str, date, None]) – Start date (YYYY-MM-DD or date object)

  • end_date (Union[str, date, None]) – End date (YYYY-MM-DD or date object)

Return type:

dict[str, Any]

Returns:

Dictionary with paginated history data

getDailyBankSubindexGraph()[source]

Get NEPSE Daily Bank Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyDevelopmentBankSubindexGraph()[source]

Get NEPSE Development Bank Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyFinanceSubindexGraph()[source]

Get NEPSE Daily Finance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyFloatIndexGraph()[source]

Get NEPSE Daily Float Index Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyHotelTourismSubindexGraph()[source]

Gat NEPSE Daily Hotel Tourism Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyHydroSubindexGraph()[source]

Get NEPSE Daily Hydro Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyInvestmentSubindexGraph()[source]

Get NEPSE Daily Investment Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyLifeInsuranceSubindexGraph()[source]

Get NEPSE Daily Life Insurance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyManufacturingSubindexGraph()[source]

Get NEPSE Daily Manufacturing Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyMicrofinanceSubindexGraph()[source]

Get NEPSE Daily Microfinance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyMutualfundSubindexGraph()[source]

Get NEPSE Daily Mutual Fund Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyNepseIndexGraph()[source]

Get price volume history for a business date.

Return type:

list[Any]

getDailyNonLifeInsuranceSubindexGraph()[source]

Get NEPSE Daily Non Life Insurance Subindex Graph data.

Returns:

_description_

Return type:

list[Any]

getDailyOthersSubindexGraph()[source]

Get NEPSE Daily Other Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyScripPriceGraph(symbol)[source]

Get daily price graph data for a scrip.

Parameters:

symbol (str) – Company symbol

Return type:

dict[str, Any]

Returns:

Graph data dictionary

getDailySensitiveFloatIndexGraph()[source]

Get NEPSE Daily Sensitive Float Index Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailySensitiveIndexGraph()[source]

Get NEPSE Daily Sensitive Index Graph.

Returns:

_description_

Return type:

list[Any]

getDailyTradingSubindexGraph()[source]

Get NEPSE Daily Trading Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDebentureAndBondList(bond_type='debenture')[source]

Get list of debentures and bonds.

Return type:

list[dict[str, Any]]

Parameters:

bond_type (str)

getFloorSheet(show_progress=False, paginated=False, page=None)[source]

Get floor sheet data.

Parameters:
  • show_progress (bool) – Show progress bar during download

  • paginated (bool) – Return list of pages instead of flattened list

  • page (Optional[int]) – Get specific page number (0-indexed)

Return type:

Union[list[dict[str, Any]], list[list[dict[str, Any]]], dict[str, Any]]

Returns:

Floor sheet data (format depends on parameters)

getFloorSheetOf(symbol, business_date=None, size=500)[source]

Get floor sheet for a specific company.

Parameters:
  • symbol (str) – Company symbol

  • business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

  • size (int)

Return type:

list[dict[str, Any]]

Returns:

List of floor sheet records

getHolidayList(year=2025)[source]

Get list of market holidays for specified year.

Return type:

list[dict[str, Any]]

Parameters:

year (int)

getNepseNotice(page=0, size=10)[source]

Get NEPSE Notice data.

Parameters:
  • page (int, optional) – _description_. Defaults to 0.

  • size (int, optional) – _description_. Defaults to 10.

Returns:

_description_

Return type:

dict[str, Any]

getNewsAndAlertList(page=0, page_size=100, is_strip_tags=True)[source]

Get list of News and Alert.

Return type:

dict[str, Any]

Parameters:
  • page (int)

  • page_size (int)

  • is_strip_tags (bool)

getPOSTPayloadID()[source]

Generate general payload ID.

Return type:

int

getPOSTPayloadIDForFloorSheet(business_date=None)[source]

Generate payload ID for floor sheet requests.

Parameters:

business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

Return type:

int

Returns:

Payload ID integer

getPOSTPayloadIDForScrips()[source]

Generate payload ID for scrip-related requests.

Return type:

int

getPressRelease(page=0, size=20)[source]

Get list of Press release.

Parameters:
  • page (int, optional) – _description_. Defaults to None.

  • size (int, optional) – _description_. Defaults to 20.

Returns:

Response containing press releases with full file paths

Return type:

dict[str, Any]

getPriceVolumeHistory(business_date=None)[source]

Get price volume history for a business date.

Return type:

dict[str, Any]

Parameters:

business_date (str | None)

getSectorScrips()[source]

Get scrips grouped by sector.

Return type:

dict[str, list[str]]

Returns:

Dictionary mapping sector name to list of symbols

getSecurityIDKeyMap(force_update=False)[source]

Get mapping of security symbols to IDs.

Parameters:

force_update (bool) – Force refresh of cached data

Return type:

dict[str, int]

Returns:

Dictionary mapping symbol to security ID

getSecurityList()[source]

Get list of all securities (non-delisted).

Return type:

list[dict[str, Any]]

Returns:

List of security dictionaries

getSymbolMarketDepth(symbol)[source]

Get market depth for a symbol.

Parameters:

symbol (str) – Company symbol

Return type:

dict[str, Any]

Returns:

Market depth data

init_client(tls_verify)[source]

Initialize HTTP client with specified settings.

Parameters:

tls_verify (bool) – Whether to verify TLS certificates

Return type:

None

requestGETAPI(url, include_authorization_headers=True)[source]

Make GET request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • include_authorization_headers (bool) – Whether to include auth headers

Return type:

Any

Returns:

Parsed response data

requestPOSTAPI(url, payload_generator)[source]

Make POST request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • payload_generator – Function to generate payload

Return type:

Any

Returns:

Parsed response data

headers: dict[str, str]
company_symbol_id_keymap: Optional[dict[str, int]]
security_symbol_id_keymap: Optional[dict[str, int]]
company_list: Optional[list[dict]]
security_list: Optional[list[dict]]
holiday_list: Optional[list[dict]]
sector_scrips: Optional[dict[str, list[str]]]
class nepse_client.AsyncNepseClient[source]

Bases: _NepseBase

Asynchronous client for NEPSE API.

This client provides non-blocking async methods to access Nepal Stock Exchange data, enabling concurrent operations and better performance for bulk requests.

Parameters:
  • logger (Optional[Logger]) – Optional custom logger instance

  • mask_request_data (bool) – Whether to mask sensitive data in logs (default: True)

  • timeout (float) – Request timeout in seconds (default: 100.0)

Example

Basic usage:

import asyncio
from nepse_client import AsyncNepseClient

async def main():
      client = AsyncNepseClient()

      # Get market status
      status = await client.getMarketStatus()
      print(f"Market is {status['isOpen']}")

      # Concurrent requests
      status, summary, gainers = await asyncio.gather(
         client.getMarketStatus(),
         client.getSummary(),
         client.getTopGainers()
      )

asyncio.run(main())

Note

All methods are coroutines and must be awaited. The client automatically manages authentication tokens and handles token expiration.

async __aenter__()[source]

Async context manager entry.

async __aexit__(exc_type, exc_val, exc_tb)[source]

Async context manager exit - cleanup resources.

__init__(logger=None, mask_request_data=True, timeout=100.0)[source]

Initialize asynchronous NEPSE client.

Parameters:
  • logger (Logger | None)

  • mask_request_data (bool)

  • timeout (float)

async close()[source]

Close HTTP client and cleanup resources.

Return type:

None

async getAuthorizationHeaders()[source]

Get headers with authorization token.

Return type:

dict[str, str]

Returns:

Dictionary of HTTP headers

async getCompanyDetails(symbol)[source]

Get detailed information for a specific company.

Return type:

dict[str, Any]

Parameters:

symbol (str)

async getCompanyIDKeyMap(force_update=False)[source]

Get mapping of company symbols to IDs.

Return type:

dict[str, int]

Parameters:

force_update (bool)

async getCompanyList()[source]

Get list of all listed companies.

Return type:

list[dict[str, Any]]

async getCompanyPriceVolumeHistory(symbol, start_date=None, end_date=None)[source]

Get price and volume history for a company.

Return type:

dict[str, Any]

Parameters:
  • symbol (str)

  • start_date (str | date | None)

  • end_date (str | date | None)

async getDailyScripPriceGraph(symbol)[source]

Get daily price graph data for a scrip.

Return type:

dict[str, Any]

Parameters:

symbol (str)

async getFloorSheet(show_progress=False)[source]

Get complete floor sheet data.

Parameters:

show_progress (bool) – Show progress bar during download

Return type:

list[dict[str, Any]]

Returns:

List of all floor sheet records

async getFloorSheetOf(symbol, business_date=None)[source]

Get floor sheet for a specific company.

Return type:

list[dict[str, Any]]

Parameters:
  • symbol (str)

  • business_date (str | date | None)

async getLiveMarket()[source]

Get live market data.

Return type:

dict[str, Any]

async getMarketStatus()[source]

Get current market status (open/closed).

Return type:

dict[str, Any]

async getNepseIndex()[source]

Get NEPSE index data.

Return type:

dict[str, Any]

async getNepseSubIndices()[source]

Get all NEPSE sub-indices.

Return type:

list[dict[str, Any]]

async getPOSTPayloadID()[source]

Generate general payload ID.

Return type:

int

async getPOSTPayloadIDForFloorSheet(business_date=None)[source]

Generate payload ID for floor sheet requests.

Parameters:

business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

Return type:

int

Returns:

Payload ID integer

async getPOSTPayloadIDForScrips()[source]

Generate payload ID for scrip-related requests.

Return type:

int

async getPriceVolume()[source]

Get current price and volume data for all securities.

Return type:

list[dict[str, Any]]

async getSectorScrips()[source]

Get scrips grouped by sector.

Return type:

dict[str, list[str]]

async getSecurityIDKeyMap(force_update=False)[source]

Get mapping of security symbols to IDs.

Return type:

dict[str, int]

Parameters:

force_update (bool)

async getSecurityList()[source]

Get list of all securities (non-delisted).

Return type:

list[dict[str, Any]]

async getSummary()[source]

Get market summary with turnover, trades, etc.

Return type:

dict[str, Any]

async getSupplyDemand()[source]

Get supply and demand data.

Return type:

dict[str, Any]

async getSymbolMarketDepth(symbol)[source]

Get market depth for a symbol.

Return type:

dict[str, Any]

Parameters:

symbol (str)

async getTopGainers()[source]

Get list of top gaining stocks.

Return type:

list[dict[str, Any]]

async getTopLosers()[source]

Get list of top losing stocks.

Return type:

list[dict[str, Any]]

async getTopTenTradeScrips()[source]

Get top 10 scrips by trade volume.

Return type:

list[dict[str, Any]]

async getTopTenTransactionScrips()[source]

Get top 10 scrips by transaction count.

Return type:

list[dict[str, Any]]

async getTopTenTurnoverScrips()[source]

Get top 10 scrips by turnover.

Return type:

list[dict[str, Any]]

async getTradingAverage(business_date=None, nDays=180)[source]

Get trading average data.

Return type:

dict[str, Any]

Parameters:
  • business_date (str | None)

  • nDays (int)

init_client(tls_verify)[source]

Initialize async HTTP client with specified settings.

Parameters:

tls_verify (bool) – Whether to verify TLS certificates

Return type:

None

async requestGETAPI(url, include_authorization_headers=True)[source]

Make async GET request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • include_authorization_headers (bool) – Whether to include auth headers

Return type:

Any

Returns:

Parsed response data

async requestPOSTAPI(url, payload_generator)[source]

Make async POST request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • payload_generator – Async function to generate payload

Return type:

Any

Returns:

Parsed response data

headers: dict[str, str]
company_symbol_id_keymap: Optional[dict[str, int]]
security_symbol_id_keymap: Optional[dict[str, int]]
company_list: Optional[list[dict]]
security_list: Optional[list[dict]]
holiday_list: Optional[list[dict]]
sector_scrips: Optional[dict[str, list[str]]]
exception nepse_client.NepseError[source]

Bases: Exception

Base exception class for all NEPSE-related errors.

All custom exceptions in this library inherit from this class, allowing for easy catch-all error handling.

message

Human-readable error description

status_code

HTTP status code (if applicable)

response_data

Raw response data from the API

request_data

Original request data

__init__(message, status_code=None, response_data=None, request_data=None)[source]

Initialize NepseError.

Parameters:
  • message (str) – Error description

  • status_code (Optional[int]) – HTTP status code

  • response_data (Optional[Any]) – Response from the API

  • request_data (Optional[dict[str, Any]]) – Original request data

__repr__()[source]

Return detailed representation of the error.

Return type:

str

__str__()[source]

Return string representation of the error.

Return type:

str

to_dict()[source]

Convert exception to dictionary for logging/serialization.

Return type:

dict[str, Any]

Returns:

Dictionary representation of the exception

exception nepse_client.NepseClientError[source]

Bases: NepseError

Raised when client sends an invalid request (4xx errors).

This typically indicates: - Invalid parameters - Missing required fields - Malformed request data - Invalid company symbol

Example

>>> try:
...     client.getCompanyDetails("INVALID")
... except NepseClientError as e:
...     print(f"Invalid request: {e}")
__init__(message='Invalid client request', status_code=400, response_data=None, request_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

  • request_data (dict[str, Any] | None)

exception nepse_client.NepseServerError[source]

Bases: NepseError

Generic server error for 5xx status codes.

This indicates an error on the NEPSE server side. Common causes: - Internal server error (500) - Service unavailable (503) - Gateway timeout (504)

Recommended action: Retry with exponential backoff or contact support.

__init__(message='Server error occurred', status_code=500, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

exception nepse_client.NepseAuthenticationError[source]

Bases: NepseError

Raised when access token has expired (401 Unauthorized).

This exception is typically handled automatically by the client, which will refresh the token and retry the request.

Note

Users usually don’t need to handle this exception directly as the client manages token refresh automatically.

__init__(message='Authentication token expired', status_code=401, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

exception nepse_client.NepseNetworkError[source]

Bases: NepseError

Raised for general network or unexpected HTTP issues.

This covers: - Connection timeouts - DNS resolution failures - SSL/TLS errors - Unexpected response formats - Network interruptions

Recommended action: Check network connectivity and retry.

__init__(message='Network error occurred', status_code=None, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int | None)

  • response_data (Any | None)

exception nepse_client.NepseValidationError[source]

Bases: NepseError

Raised when input validation fails before making API request.

This is raised for client-side validation errors such as: - Invalid date formats - Out of range values - Missing required parameters - Invalid data types

Example

>>> try:
...     client.getCompanyPriceVolumeHistory("NABIL", start_date="invalid")
... except NepseValidationError as e:
...     print(f"Validation error: {e}")
__init__(message='Input validation failed', field=None, value=None)[source]

Initialize validation error.

Parameters:
  • message (str) – Error description

  • field (Optional[str]) – Name of the invalid field

  • value (Optional[Any]) – Invalid value provided

exception nepse_client.NepseBadGatewayError[source]

Bases: NepseError

Raised when server returns 502 Bad Gateway.

This typically indicates: - Server temporarily unavailable - Upstream server issues - Network problems between servers

Recommended action: Retry the request after a short delay.

__init__(message='Bad Gateway - Server temporarily unavailable', status_code=502, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

exception nepse_client.NepseRateLimitError[source]

Bases: NepseError

Raised when API rate limit is exceeded (429 Too Many Requests).

retry_after

Seconds to wait before retrying (if provided by server)

__init__(message='Rate limit exceeded', status_code=429, retry_after=None)[source]

Initialize rate limit error.

Parameters:
  • message (str) – Error description

  • status_code (int) – HTTP status code

  • retry_after (Optional[int]) – Seconds to wait before retry

exception nepse_client.NepseDataNotFoundError[source]

Bases: NepseError

Raised when requested data is not found.

This is used when: - Company symbol doesn’t exist - No data available for requested date - Empty result sets

Example

>>> try:
...     client.getFloorSheetOf("INVALID", "2024-01-01")
... except NepseDataNotFoundError as e:
...     print(f"Data not found: {e}")
__init__(message='Requested data not found', resource=None)[source]

Initialize data not found error.

Parameters:
  • message (str) – Error description

  • resource (Optional[str]) – Resource that was not found

exception nepse_client.NepseTimeoutError[source]

Bases: NepseError

Raised when request times out.

This occurs when the server doesn’t respond within the specified timeout period.

timeout

Timeout value in seconds

__init__(message='Request timeout', timeout=None)[source]

Initialize timeout error.

Parameters:
  • message (str) – Error description

  • timeout (Optional[float]) – Timeout value in seconds

exception nepse_client.NepseConnectionError[source]

Bases: NepseError

Raised when connection to NEPSE server fails.

This is different from NepseNetworkError as it specifically indicates inability to establish a connection.

__init__(message='Failed to connect to NEPSE server')[source]

Initialize the exception with a default message.

Parameters:

message (str)

exception nepse_client.NepseConfigurationError[source]

Bases: NepseError

Raised when there’s an issue with client configuration.

This includes: - Missing required configuration files - Invalid configuration values - Corrupted data files

__init__(message='Configuration error')[source]

Initialize the exception with a default message.

Parameters:

message (str)

Main Classes

NepseClient

class nepse_client.NepseClient[source]

Bases: _NepseBase

Synchronous client for NEPSE API.

This client provides blocking methods to access Nepal Stock Exchange data including market status, company information, trading data, and more.

Parameters:
  • logger (Optional[Logger]) – Optional custom logger instance

  • mask_request_data (bool) – Whether to mask sensitive data in logs (default: True)

  • timeout (float) – Request timeout in seconds (default: 100.0)

Example

Basic usage:

from nepse_client import NepseClient

client = NepseClient()

# Get market status
status = client.getMarketStatus()
print(f"Market is {status['isOpen']}")

# Get company details
nabil = client.getCompanyDetails("NABIL")
print(f"NABIL LTP: {nabil['lastTradedPrice']}")

Note

The client automatically manages authentication tokens and handles token expiration transparently.

The synchronous client for NEPSE API.

Example:

from nepse_client import NepseClient

client = NepseClient()
status = client.getMarketStatus()
print(status)
__init__(logger=None, mask_request_data=True, timeout=100.0)[source]

Initialize synchronous NEPSE client.

Parameters:
  • logger (Logger | None)

  • mask_request_data (bool)

  • timeout (float)

init_client(tls_verify)[source]

Initialize HTTP client with specified settings.

Parameters:

tls_verify (bool) – Whether to verify TLS certificates

Return type:

None

__enter__()[source]

Context manager entry.

__exit__(exc_type, exc_val, exc_tb)[source]

Context manager exit - cleanup resources.

close()[source]

Close HTTP client and cleanup resources.

Return type:

None

requestGETAPI(url, include_authorization_headers=True)[source]

Make GET request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • include_authorization_headers (bool) – Whether to include auth headers

Return type:

Any

Returns:

Parsed response data

requestPOSTAPI(url, payload_generator)[source]

Make POST request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • payload_generator – Function to generate payload

Return type:

Any

Returns:

Parsed response data

getAuthorizationHeaders()[source]

Get headers with authorization token.

Return type:

dict[str, str]

Returns:

Dictionary of HTTP headers

getPOSTPayloadIDForScrips()[source]

Generate payload ID for scrip-related requests.

Return type:

int

getPOSTPayloadID()[source]

Generate general payload ID.

Return type:

int

getPOSTPayloadIDForFloorSheet(business_date=None)[source]

Generate payload ID for floor sheet requests.

Parameters:

business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

Return type:

int

Returns:

Payload ID integer

getCompanyList()[source]

Get list of all listed companies.

Return type:

list[dict[str, Any]]

Returns:

List of company dictionaries

Note

Results are cached internally. Subsequent calls return cached data unless cache is cleared.

getSecurityList()[source]

Get list of all securities (non-delisted).

Return type:

list[dict[str, Any]]

Returns:

List of security dictionaries

getCompanyIDKeyMap(force_update=False)[source]

Get mapping of company symbols to IDs.

Parameters:

force_update (bool) – Force refresh of cached data

Return type:

dict[str, int]

Returns:

Dictionary mapping symbol to company ID

getSecurityIDKeyMap(force_update=False)[source]

Get mapping of security symbols to IDs.

Parameters:

force_update (bool) – Force refresh of cached data

Return type:

dict[str, int]

Returns:

Dictionary mapping symbol to security ID

getSectorScrips()[source]

Get scrips grouped by sector.

Return type:

dict[str, list[str]]

Returns:

Dictionary mapping sector name to list of symbols

getCompanyDetails(symbol)[source]

Get detailed information for a specific company.

Parameters:

symbol (str) – Company stock symbol (e.g., “NABIL”)

Return type:

dict[str, Any]

Returns:

Dictionary with company details

Raises:

KeyError – If symbol not found

getCompanyFinancialDetails(company_id=None)[source]

Get financial details for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing financial details for the company.

Each dictionary might include keys like ‘period’, ‘financialMetrics’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with ‘fullFilePath’ and ‘fullEncryptedPath’ keys for

Return type:

list

getCompanyAGM(company_id=None)[source]

Get Annual General Meeting (AGM) information for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing AGM details for the company.

Each dictionary might include keys like ‘meetingDate’, ‘agenda’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with a ‘fullFilePath’ key for document access.

Return type:

list

getCompanyDividend(company_id=None)[source]

Get dividend information for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing dividend details for the company.

Each dictionary might include keys like ‘dividendType’, ‘rate’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with a ‘fullFilePath’ key for document access.

Return type:

list

getCompanyMarketDepth(company_id=None)[source]

Get market depth information for a specific company.

Market depth typically includes buy and sell orders at various price levels.

Parameters:

company_id (str, optional) – The unique identifier (symbol or code) for the company/security. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list containing market depth data for the company.

The structure of the data depends on the API response, but it usually includes buy/sell orders with prices and volumes. Returns an empty list if no data is found or an error occurs during the API request.

Return type:

list

getCompanyPriceVolumeHistory(symbol, start_date=None, end_date=None)[source]

Get price and volume history for a company.

Parameters:
  • symbol (str) – Company symbol

  • start_date (Union[str, date, None]) – Start date (YYYY-MM-DD or date object)

  • end_date (Union[str, date, None]) – End date (YYYY-MM-DD or date object)

Return type:

dict[str, Any]

Returns:

Dictionary with paginated history data

getDailyScripPriceGraph(symbol)[source]

Get daily price graph data for a scrip.

Parameters:

symbol (str) – Company symbol

Return type:

dict[str, Any]

Returns:

Graph data dictionary

getFloorSheet(show_progress=False, paginated=False, page=None)[source]

Get floor sheet data.

Parameters:
  • show_progress (bool) – Show progress bar during download

  • paginated (bool) – Return list of pages instead of flattened list

  • page (Optional[int]) – Get specific page number (0-indexed)

Return type:

Union[list[dict[str, Any]], list[list[dict[str, Any]]], dict[str, Any]]

Returns:

Floor sheet data (format depends on parameters)

getFloorSheetOf(symbol, business_date=None, size=500)[source]

Get floor sheet for a specific company.

Parameters:
  • symbol (str) – Company symbol

  • business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

  • size (int)

Return type:

list[dict[str, Any]]

Returns:

List of floor sheet records

getSymbolMarketDepth(symbol)[source]

Get market depth for a symbol.

Parameters:

symbol (str) – Company symbol

Return type:

dict[str, Any]

Returns:

Market depth data

getHolidayList(year=2025)[source]

Get list of market holidays for specified year.

Return type:

list[dict[str, Any]]

Parameters:

year (int)

getDebentureAndBondList(bond_type='debenture')[source]

Get list of debentures and bonds.

Return type:

list[dict[str, Any]]

Parameters:

bond_type (str)

getCompanyNewsList(page=0, page_size=100, is_strip_tags=True)[source]

Get list of company news.

Return type:

dict[str, Any]

Parameters:
  • page (int)

  • page_size (int)

  • is_strip_tags (bool)

getNewsAndAlertList(page=0, page_size=100, is_strip_tags=True)[source]

Get list of News and Alert.

Return type:

dict[str, Any]

Parameters:
  • page (int)

  • page_size (int)

  • is_strip_tags (bool)

getPressRelease(page=0, size=20)[source]

Get list of Press release.

Parameters:
  • page (int, optional) – _description_. Defaults to None.

  • size (int, optional) – _description_. Defaults to 20.

Returns:

Response containing press releases with full file paths

Return type:

dict[str, Any]

getNepseNotice(page=0, size=10)[source]

Get NEPSE Notice data.

Parameters:
  • page (int, optional) – _description_. Defaults to 0.

  • size (int, optional) – _description_. Defaults to 10.

Returns:

_description_

Return type:

dict[str, Any]

getPriceVolumeHistory(business_date=None)[source]

Get price volume history for a business date.

Return type:

dict[str, Any]

Parameters:

business_date (str | None)

getDailyNepseIndexGraph()[source]

Get price volume history for a business date.

Return type:

list[Any]

getDailySensitiveIndexGraph()[source]

Get NEPSE Daily Sensitive Index Graph.

Returns:

_description_

Return type:

list[Any]

getDailyFloatIndexGraph()[source]

Get NEPSE Daily Float Index Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailySensitiveFloatIndexGraph()[source]

Get NEPSE Daily Sensitive Float Index Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyBankSubindexGraph()[source]

Get NEPSE Daily Bank Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyDevelopmentBankSubindexGraph()[source]

Get NEPSE Development Bank Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyFinanceSubindexGraph()[source]

Get NEPSE Daily Finance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyHotelTourismSubindexGraph()[source]

Gat NEPSE Daily Hotel Tourism Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyHydroSubindexGraph()[source]

Get NEPSE Daily Hydro Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyInvestmentSubindexGraph()[source]

Get NEPSE Daily Investment Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyLifeInsuranceSubindexGraph()[source]

Get NEPSE Daily Life Insurance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyManufacturingSubindexGraph()[source]

Get NEPSE Daily Manufacturing Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyMicrofinanceSubindexGraph()[source]

Get NEPSE Daily Microfinance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyMutualfundSubindexGraph()[source]

Get NEPSE Daily Mutual Fund Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyNonLifeInsuranceSubindexGraph()[source]

Get NEPSE Daily Non Life Insurance Subindex Graph data.

Returns:

_description_

Return type:

list[Any]

getDailyOthersSubindexGraph()[source]

Get NEPSE Daily Other Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyTradingSubindexGraph()[source]

Get NEPSE Daily Trading Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

headers: dict[str, str]
company_symbol_id_keymap: Optional[dict[str, int]]
security_symbol_id_keymap: Optional[dict[str, int]]
company_list: Optional[list[dict]]
security_list: Optional[list[dict]]
holiday_list: Optional[list[dict]]
sector_scrips: Optional[dict[str, list[str]]]

AsyncNepseClient

class nepse_client.AsyncNepseClient[source]

Bases: _NepseBase

Asynchronous client for NEPSE API.

This client provides non-blocking async methods to access Nepal Stock Exchange data, enabling concurrent operations and better performance for bulk requests.

Parameters:
  • logger (Optional[Logger]) – Optional custom logger instance

  • mask_request_data (bool) – Whether to mask sensitive data in logs (default: True)

  • timeout (float) – Request timeout in seconds (default: 100.0)

Example

Basic usage:

import asyncio
from nepse_client import AsyncNepseClient

async def main():
      client = AsyncNepseClient()

      # Get market status
      status = await client.getMarketStatus()
      print(f"Market is {status['isOpen']}")

      # Concurrent requests
      status, summary, gainers = await asyncio.gather(
         client.getMarketStatus(),
         client.getSummary(),
         client.getTopGainers()
      )

asyncio.run(main())

Note

All methods are coroutines and must be awaited. The client automatically manages authentication tokens and handles token expiration.

The asynchronous client for NEPSE API.

Example:

import asyncio
from nepse_client import AsyncNepseClient

async def main():
   client = AsyncNepseClient()
   status = await client.getMarketStatus()
   print(status)

asyncio.run(main())
__init__(logger=None, mask_request_data=True, timeout=100.0)[source]

Initialize asynchronous NEPSE client.

Parameters:
  • logger (Logger | None)

  • mask_request_data (bool)

  • timeout (float)

init_client(tls_verify)[source]

Initialize async HTTP client with specified settings.

Parameters:

tls_verify (bool) – Whether to verify TLS certificates

Return type:

None

async __aenter__()[source]

Async context manager entry.

async __aexit__(exc_type, exc_val, exc_tb)[source]

Async context manager exit - cleanup resources.

async close()[source]

Close HTTP client and cleanup resources.

Return type:

None

async requestGETAPI(url, include_authorization_headers=True)[source]

Make async GET request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • include_authorization_headers (bool) – Whether to include auth headers

Return type:

Any

Returns:

Parsed response data

async requestPOSTAPI(url, payload_generator)[source]

Make async POST request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • payload_generator – Async function to generate payload

Return type:

Any

Returns:

Parsed response data

async getAuthorizationHeaders()[source]

Get headers with authorization token.

Return type:

dict[str, str]

Returns:

Dictionary of HTTP headers

async getPOSTPayloadIDForScrips()[source]

Generate payload ID for scrip-related requests.

Return type:

int

async getPOSTPayloadID()[source]

Generate general payload ID.

Return type:

int

async getPOSTPayloadIDForFloorSheet(business_date=None)[source]

Generate payload ID for floor sheet requests.

Parameters:

business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

Return type:

int

Returns:

Payload ID integer

async getMarketStatus()[source]

Get current market status (open/closed).

Return type:

dict[str, Any]

async getPriceVolume()[source]

Get current price and volume data for all securities.

Return type:

list[dict[str, Any]]

async getSummary()[source]

Get market summary with turnover, trades, etc.

Return type:

dict[str, Any]

async getTopGainers()[source]

Get list of top gaining stocks.

Return type:

list[dict[str, Any]]

async getTopLosers()[source]

Get list of top losing stocks.

Return type:

list[dict[str, Any]]

async getTopTenTradeScrips()[source]

Get top 10 scrips by trade volume.

Return type:

list[dict[str, Any]]

async getTopTenTransactionScrips()[source]

Get top 10 scrips by transaction count.

Return type:

list[dict[str, Any]]

async getTopTenTurnoverScrips()[source]

Get top 10 scrips by turnover.

Return type:

list[dict[str, Any]]

async getSupplyDemand()[source]

Get supply and demand data.

Return type:

dict[str, Any]

async getNepseIndex()[source]

Get NEPSE index data.

Return type:

dict[str, Any]

async getNepseSubIndices()[source]

Get all NEPSE sub-indices.

Return type:

list[dict[str, Any]]

async getLiveMarket()[source]

Get live market data.

Return type:

dict[str, Any]

async getTradingAverage(business_date=None, nDays=180)[source]

Get trading average data.

Return type:

dict[str, Any]

Parameters:
  • business_date (str | None)

  • nDays (int)

async getCompanyList()[source]

Get list of all listed companies.

Return type:

list[dict[str, Any]]

async getSecurityList()[source]

Get list of all securities (non-delisted).

Return type:

list[dict[str, Any]]

async getCompanyIDKeyMap(force_update=False)[source]

Get mapping of company symbols to IDs.

Return type:

dict[str, int]

Parameters:

force_update (bool)

async getSecurityIDKeyMap(force_update=False)[source]

Get mapping of security symbols to IDs.

Return type:

dict[str, int]

Parameters:

force_update (bool)

async getSectorScrips()[source]

Get scrips grouped by sector.

Return type:

dict[str, list[str]]

async getCompanyDetails(symbol)[source]

Get detailed information for a specific company.

Return type:

dict[str, Any]

Parameters:

symbol (str)

async getCompanyPriceVolumeHistory(symbol, start_date=None, end_date=None)[source]

Get price and volume history for a company.

Return type:

dict[str, Any]

Parameters:
  • symbol (str)

  • start_date (str | date | None)

  • end_date (str | date | None)

async getDailyScripPriceGraph(symbol)[source]

Get daily price graph data for a scrip.

Return type:

dict[str, Any]

Parameters:

symbol (str)

async getFloorSheet(show_progress=False)[source]

Get complete floor sheet data.

Parameters:

show_progress (bool) – Show progress bar during download

Return type:

list[dict[str, Any]]

Returns:

List of all floor sheet records

async getFloorSheetOf(symbol, business_date=None)[source]

Get floor sheet for a specific company.

Return type:

list[dict[str, Any]]

Parameters:
  • symbol (str)

  • business_date (str | date | None)

async getSymbolMarketDepth(symbol)[source]

Get market depth for a symbol.

Return type:

dict[str, Any]

Parameters:

symbol (str)

headers: dict[str, str]
company_symbol_id_keymap: Optional[dict[str, int]]
security_symbol_id_keymap: Optional[dict[str, int]]
company_list: Optional[list[dict]]
security_list: Optional[list[dict]]
holiday_list: Optional[list[dict]]
sector_scrips: Optional[dict[str, list[str]]]

Package Metadata

Version

nepse_client.__version__ = 1.0.0

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

Author

nepse_client.__author__ = Amrit Giri

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

Submodules

client

Base client implementation for NEPSE API.

This module provides the foundation for both sync and async clients, including common utilities, configuration loading, and response handling.

nepse_client.client.mask_sensitive_data(data, keys=('token', 'password', 'Authorization'))[source]

Mask sensitive fields in data for safe logging.

Parameters:
  • data (dict[str, Any]) – Dictionary containing potentially sensitive data

  • keys (tuple) – Tuple of keys to mask

Return type:

dict[str, Any]

Returns:

Dictionary with masked sensitive values

nepse_client.client.safe_serialize(obj)[source]

Safely serialize objects for logging.

Parameters:

obj (Any) – Object to serialize

Return type:

Union[str, dict, list]

Returns:

Serialized representation

sync_client

Synchronous NEPSE client implementation.

This module provides a blocking, synchronous interface to the NEPSE API, suitable for scripts, notebooks, and applications that don’t require concurrency.

class nepse_client.sync_client.NepseClient[source]

Bases: _NepseBase

Synchronous client for NEPSE API.

This client provides blocking methods to access Nepal Stock Exchange data including market status, company information, trading data, and more.

Parameters:
  • logger (Optional[Logger]) – Optional custom logger instance

  • mask_request_data (bool) – Whether to mask sensitive data in logs (default: True)

  • timeout (float) – Request timeout in seconds (default: 100.0)

Example

Basic usage:

from nepse_client import NepseClient

client = NepseClient()

# Get market status
status = client.getMarketStatus()
print(f"Market is {status['isOpen']}")

# Get company details
nabil = client.getCompanyDetails("NABIL")
print(f"NABIL LTP: {nabil['lastTradedPrice']}")

Note

The client automatically manages authentication tokens and handles token expiration transparently.

__init__(logger=None, mask_request_data=True, timeout=100.0)[source]

Initialize synchronous NEPSE client.

Parameters:
  • logger (Logger | None)

  • mask_request_data (bool)

  • timeout (float)

init_client(tls_verify)[source]

Initialize HTTP client with specified settings.

Parameters:

tls_verify (bool) – Whether to verify TLS certificates

Return type:

None

__enter__()[source]

Context manager entry.

__exit__(exc_type, exc_val, exc_tb)[source]

Context manager exit - cleanup resources.

close()[source]

Close HTTP client and cleanup resources.

Return type:

None

requestGETAPI(url, include_authorization_headers=True)[source]

Make GET request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • include_authorization_headers (bool) – Whether to include auth headers

Return type:

Any

Returns:

Parsed response data

requestPOSTAPI(url, payload_generator)[source]

Make POST request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • payload_generator – Function to generate payload

Return type:

Any

Returns:

Parsed response data

getAuthorizationHeaders()[source]

Get headers with authorization token.

Return type:

dict[str, str]

Returns:

Dictionary of HTTP headers

getPOSTPayloadIDForScrips()[source]

Generate payload ID for scrip-related requests.

Return type:

int

getPOSTPayloadID()[source]

Generate general payload ID.

Return type:

int

getPOSTPayloadIDForFloorSheet(business_date=None)[source]

Generate payload ID for floor sheet requests.

Parameters:

business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

Return type:

int

Returns:

Payload ID integer

getCompanyList()[source]

Get list of all listed companies.

Return type:

list[dict[str, Any]]

Returns:

List of company dictionaries

Note

Results are cached internally. Subsequent calls return cached data unless cache is cleared.

getSecurityList()[source]

Get list of all securities (non-delisted).

Return type:

list[dict[str, Any]]

Returns:

List of security dictionaries

getCompanyIDKeyMap(force_update=False)[source]

Get mapping of company symbols to IDs.

Parameters:

force_update (bool) – Force refresh of cached data

Return type:

dict[str, int]

Returns:

Dictionary mapping symbol to company ID

getSecurityIDKeyMap(force_update=False)[source]

Get mapping of security symbols to IDs.

Parameters:

force_update (bool) – Force refresh of cached data

Return type:

dict[str, int]

Returns:

Dictionary mapping symbol to security ID

getSectorScrips()[source]

Get scrips grouped by sector.

Return type:

dict[str, list[str]]

Returns:

Dictionary mapping sector name to list of symbols

getCompanyDetails(symbol)[source]

Get detailed information for a specific company.

Parameters:

symbol (str) – Company stock symbol (e.g., “NABIL”)

Return type:

dict[str, Any]

Returns:

Dictionary with company details

Raises:

KeyError – If symbol not found

getCompanyFinancialDetails(company_id=None)[source]

Get financial details for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing financial details for the company.

Each dictionary might include keys like ‘period’, ‘financialMetrics’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with ‘fullFilePath’ and ‘fullEncryptedPath’ keys for

Return type:

list

getCompanyAGM(company_id=None)[source]

Get Annual General Meeting (AGM) information for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing AGM details for the company.

Each dictionary might include keys like ‘meetingDate’, ‘agenda’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with a ‘fullFilePath’ key for document access.

Return type:

list

getCompanyDividend(company_id=None)[source]

Get dividend information for a specific company.

Parameters:

company_id (str, optional) – The unique identifier for the company. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list of dictionaries containing dividend details for the company.

Each dictionary might include keys like ‘dividendType’, ‘rate’, ‘applicationDocumentDetailsList’, etc., as returned by the API. Returns an empty list if no data is found or an error occurs during the API request or processing.

The ‘applicationDocumentDetailsList’ within each item may be augmented with a ‘fullFilePath’ key for document access.

Return type:

list

getCompanyMarketDepth(company_id=None)[source]

Get market depth information for a specific company.

Market depth typically includes buy and sell orders at various price levels.

Parameters:

company_id (str, optional) – The unique identifier (symbol or code) for the company/security. If not provided, the behavior depends on the API endpoint’s default or requirements.

Returns:

A list containing market depth data for the company.

The structure of the data depends on the API response, but it usually includes buy/sell orders with prices and volumes. Returns an empty list if no data is found or an error occurs during the API request.

Return type:

list

getCompanyPriceVolumeHistory(symbol, start_date=None, end_date=None)[source]

Get price and volume history for a company.

Parameters:
  • symbol (str) – Company symbol

  • start_date (Union[str, date, None]) – Start date (YYYY-MM-DD or date object)

  • end_date (Union[str, date, None]) – End date (YYYY-MM-DD or date object)

Return type:

dict[str, Any]

Returns:

Dictionary with paginated history data

getDailyScripPriceGraph(symbol)[source]

Get daily price graph data for a scrip.

Parameters:

symbol (str) – Company symbol

Return type:

dict[str, Any]

Returns:

Graph data dictionary

getFloorSheet(show_progress=False, paginated=False, page=None)[source]

Get floor sheet data.

Parameters:
  • show_progress (bool) – Show progress bar during download

  • paginated (bool) – Return list of pages instead of flattened list

  • page (Optional[int]) – Get specific page number (0-indexed)

Return type:

Union[list[dict[str, Any]], list[list[dict[str, Any]]], dict[str, Any]]

Returns:

Floor sheet data (format depends on parameters)

getFloorSheetOf(symbol, business_date=None, size=500)[source]

Get floor sheet for a specific company.

Parameters:
  • symbol (str) – Company symbol

  • business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

  • size (int)

Return type:

list[dict[str, Any]]

Returns:

List of floor sheet records

getSymbolMarketDepth(symbol)[source]

Get market depth for a symbol.

Parameters:

symbol (str) – Company symbol

Return type:

dict[str, Any]

Returns:

Market depth data

getHolidayList(year=2025)[source]

Get list of market holidays for specified year.

Return type:

list[dict[str, Any]]

Parameters:

year (int)

getDebentureAndBondList(bond_type='debenture')[source]

Get list of debentures and bonds.

Return type:

list[dict[str, Any]]

Parameters:

bond_type (str)

getCompanyNewsList(page=0, page_size=100, is_strip_tags=True)[source]

Get list of company news.

Return type:

dict[str, Any]

Parameters:
  • page (int)

  • page_size (int)

  • is_strip_tags (bool)

getNewsAndAlertList(page=0, page_size=100, is_strip_tags=True)[source]

Get list of News and Alert.

Return type:

dict[str, Any]

Parameters:
  • page (int)

  • page_size (int)

  • is_strip_tags (bool)

getPressRelease(page=0, size=20)[source]

Get list of Press release.

Parameters:
  • page (int, optional) – _description_. Defaults to None.

  • size (int, optional) – _description_. Defaults to 20.

Returns:

Response containing press releases with full file paths

Return type:

dict[str, Any]

getNepseNotice(page=0, size=10)[source]

Get NEPSE Notice data.

Parameters:
  • page (int, optional) – _description_. Defaults to 0.

  • size (int, optional) – _description_. Defaults to 10.

Returns:

_description_

Return type:

dict[str, Any]

getPriceVolumeHistory(business_date=None)[source]

Get price volume history for a business date.

Return type:

dict[str, Any]

Parameters:

business_date (str | None)

getDailyNepseIndexGraph()[source]

Get price volume history for a business date.

Return type:

list[Any]

getDailySensitiveIndexGraph()[source]

Get NEPSE Daily Sensitive Index Graph.

Returns:

_description_

Return type:

list[Any]

getDailyFloatIndexGraph()[source]

Get NEPSE Daily Float Index Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailySensitiveFloatIndexGraph()[source]

Get NEPSE Daily Sensitive Float Index Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyBankSubindexGraph()[source]

Get NEPSE Daily Bank Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyDevelopmentBankSubindexGraph()[source]

Get NEPSE Development Bank Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyFinanceSubindexGraph()[source]

Get NEPSE Daily Finance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyHotelTourismSubindexGraph()[source]

Gat NEPSE Daily Hotel Tourism Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyHydroSubindexGraph()[source]

Get NEPSE Daily Hydro Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyInvestmentSubindexGraph()[source]

Get NEPSE Daily Investment Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyLifeInsuranceSubindexGraph()[source]

Get NEPSE Daily Life Insurance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyManufacturingSubindexGraph()[source]

Get NEPSE Daily Manufacturing Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyMicrofinanceSubindexGraph()[source]

Get NEPSE Daily Microfinance Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyMutualfundSubindexGraph()[source]

Get NEPSE Daily Mutual Fund Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyNonLifeInsuranceSubindexGraph()[source]

Get NEPSE Daily Non Life Insurance Subindex Graph data.

Returns:

_description_

Return type:

list[Any]

getDailyOthersSubindexGraph()[source]

Get NEPSE Daily Other Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

getDailyTradingSubindexGraph()[source]

Get NEPSE Daily Trading Subindex Graph Data.

Returns:

_description_

Return type:

list[Any]

headers: dict[str, str]
company_symbol_id_keymap: Optional[dict[str, int]]
security_symbol_id_keymap: Optional[dict[str, int]]
company_list: Optional[list[dict]]
security_list: Optional[list[dict]]
holiday_list: Optional[list[dict]]
sector_scrips: Optional[dict[str, list[str]]]

async_client

Asynchronous NEPSE client implementation.

This module provides a non-blocking, asynchronous interface to the NEPSE API, suitable for concurrent operations and high-performance applications.

class nepse_client.async_client.AsyncNepseClient[source]

Bases: _NepseBase

Asynchronous client for NEPSE API.

This client provides non-blocking async methods to access Nepal Stock Exchange data, enabling concurrent operations and better performance for bulk requests.

Parameters:
  • logger (Optional[Logger]) – Optional custom logger instance

  • mask_request_data (bool) – Whether to mask sensitive data in logs (default: True)

  • timeout (float) – Request timeout in seconds (default: 100.0)

Example

Basic usage:

import asyncio
from nepse_client import AsyncNepseClient

async def main():
      client = AsyncNepseClient()

      # Get market status
      status = await client.getMarketStatus()
      print(f"Market is {status['isOpen']}")

      # Concurrent requests
      status, summary, gainers = await asyncio.gather(
         client.getMarketStatus(),
         client.getSummary(),
         client.getTopGainers()
      )

asyncio.run(main())

Note

All methods are coroutines and must be awaited. The client automatically manages authentication tokens and handles token expiration.

__init__(logger=None, mask_request_data=True, timeout=100.0)[source]

Initialize asynchronous NEPSE client.

Parameters:
  • logger (Logger | None)

  • mask_request_data (bool)

  • timeout (float)

init_client(tls_verify)[source]

Initialize async HTTP client with specified settings.

Parameters:

tls_verify (bool) – Whether to verify TLS certificates

Return type:

None

async __aenter__()[source]

Async context manager entry.

async __aexit__(exc_type, exc_val, exc_tb)[source]

Async context manager exit - cleanup resources.

async close()[source]

Close HTTP client and cleanup resources.

Return type:

None

async requestGETAPI(url, include_authorization_headers=True)[source]

Make async GET request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • include_authorization_headers (bool) – Whether to include auth headers

Return type:

Any

Returns:

Parsed response data

async requestPOSTAPI(url, payload_generator)[source]

Make async POST request to NEPSE API.

Parameters:
  • url (str) – API endpoint URL

  • payload_generator – Async function to generate payload

Return type:

Any

Returns:

Parsed response data

async getAuthorizationHeaders()[source]

Get headers with authorization token.

Return type:

dict[str, str]

Returns:

Dictionary of HTTP headers

async getPOSTPayloadIDForScrips()[source]

Generate payload ID for scrip-related requests.

Return type:

int

async getPOSTPayloadID()[source]

Generate general payload ID.

Return type:

int

async getPOSTPayloadIDForFloorSheet(business_date=None)[source]

Generate payload ID for floor sheet requests.

Parameters:

business_date (Union[str, date, None]) – Business date (YYYY-MM-DD string or date object)

Return type:

int

Returns:

Payload ID integer

async getMarketStatus()[source]

Get current market status (open/closed).

Return type:

dict[str, Any]

async getPriceVolume()[source]

Get current price and volume data for all securities.

Return type:

list[dict[str, Any]]

async getSummary()[source]

Get market summary with turnover, trades, etc.

Return type:

dict[str, Any]

async getTopGainers()[source]

Get list of top gaining stocks.

Return type:

list[dict[str, Any]]

async getTopLosers()[source]

Get list of top losing stocks.

Return type:

list[dict[str, Any]]

async getTopTenTradeScrips()[source]

Get top 10 scrips by trade volume.

Return type:

list[dict[str, Any]]

async getTopTenTransactionScrips()[source]

Get top 10 scrips by transaction count.

Return type:

list[dict[str, Any]]

async getTopTenTurnoverScrips()[source]

Get top 10 scrips by turnover.

Return type:

list[dict[str, Any]]

async getSupplyDemand()[source]

Get supply and demand data.

Return type:

dict[str, Any]

async getNepseIndex()[source]

Get NEPSE index data.

Return type:

dict[str, Any]

async getNepseSubIndices()[source]

Get all NEPSE sub-indices.

Return type:

list[dict[str, Any]]

async getLiveMarket()[source]

Get live market data.

Return type:

dict[str, Any]

async getTradingAverage(business_date=None, nDays=180)[source]

Get trading average data.

Return type:

dict[str, Any]

Parameters:
  • business_date (str | None)

  • nDays (int)

async getCompanyList()[source]

Get list of all listed companies.

Return type:

list[dict[str, Any]]

async getSecurityList()[source]

Get list of all securities (non-delisted).

Return type:

list[dict[str, Any]]

async getCompanyIDKeyMap(force_update=False)[source]

Get mapping of company symbols to IDs.

Return type:

dict[str, int]

Parameters:

force_update (bool)

async getSecurityIDKeyMap(force_update=False)[source]

Get mapping of security symbols to IDs.

Return type:

dict[str, int]

Parameters:

force_update (bool)

async getSectorScrips()[source]

Get scrips grouped by sector.

Return type:

dict[str, list[str]]

async getCompanyDetails(symbol)[source]

Get detailed information for a specific company.

Return type:

dict[str, Any]

Parameters:

symbol (str)

async getCompanyPriceVolumeHistory(symbol, start_date=None, end_date=None)[source]

Get price and volume history for a company.

Return type:

dict[str, Any]

Parameters:
  • symbol (str)

  • start_date (str | date | None)

  • end_date (str | date | None)

async getDailyScripPriceGraph(symbol)[source]

Get daily price graph data for a scrip.

Return type:

dict[str, Any]

Parameters:

symbol (str)

async getFloorSheet(show_progress=False)[source]

Get complete floor sheet data.

Parameters:

show_progress (bool) – Show progress bar during download

Return type:

list[dict[str, Any]]

Returns:

List of all floor sheet records

async getFloorSheetOf(symbol, business_date=None)[source]

Get floor sheet for a specific company.

Return type:

list[dict[str, Any]]

Parameters:
  • symbol (str)

  • business_date (str | date | None)

async getSymbolMarketDepth(symbol)[source]

Get market depth for a symbol.

Return type:

dict[str, Any]

Parameters:

symbol (str)

headers: dict[str, str]
company_symbol_id_keymap: Optional[dict[str, int]]
security_symbol_id_keymap: Optional[dict[str, int]]
company_list: Optional[list[dict]]
security_list: Optional[list[dict]]
holiday_list: Optional[list[dict]]
sector_scrips: Optional[dict[str, list[str]]]

token_manager

Token management for NEPSE API authentication.

This module handles automatic token generation, refresh, and validation for both synchronous and asynchronous clients.

class nepse_client.token_manager.TokenManager[source]

Bases: _TokenManagerBase

Synchronous token manager.

Manages authentication tokens for synchronous NEPSE client, automatically refreshing tokens when they expire.

__init__(nepse)[source]

Initialize synchronous token manager.

getAccessToken()[source]

Get valid access token, refreshing if necessary.

Return type:

str

Returns:

Valid access token

getRefreshToken()[source]

Get valid refresh token, refreshing if necessary.

Return type:

str

Returns:

Valid refresh token

update()[source]

Fetch and update authentication tokens.

Return type:

None

class nepse_client.token_manager.AsyncTokenManager[source]

Bases: _TokenManagerBase

Asynchronous token manager.

Manages authentication tokens for asynchronous NEPSE client, with support for concurrent token refresh operations.

__init__(nepse)[source]

Initialize asynchronous token manager.

async getAccessToken()[source]

Get valid access token, refreshing if necessary.

Return type:

str

Returns:

Valid access token

async getRefreshToken()[source]

Get valid refresh token, refreshing if necessary.

Return type:

str

Returns:

Valid refresh token

async update()[source]

Fetch and update authentication tokens asynchronously.

Return type:

None

class nepse_client.token_manager.TokenParser[source]

Bases: object

Parse authentication tokens using WebAssembly module.

This class uses a WASM module to decode and parse the authentication tokens returned by the NEPSE API.

__init__()[source]

Initialize token parser with WASM runtime.

parse_token_response(token_response)[source]

Parse access and refresh tokens from API response.

Parameters:

token_response (dict) – Raw token response from API

Return type:

tuple[str, str]

Returns:

Tuple of (access_token, refresh_token)

dummy_id_manager

Dummy ID management for NEPSE API requests.

This module manages the generation and caching of dummy IDs used in POST request payloads, ensuring they stay synchronized with market status.

class nepse_client.dummy_id_manager.DummyIDManager[source]

Bases: _DummyIDManagerBase

Synchronous dummy ID manager.

Manages dummy IDs for synchronous NEPSE client, automatically updating when the date changes or market status is updated.

__init__(market_status_function=None, date_function=<built-in method now of type object>)[source]

Initialize synchronous dummy ID manager.

Parameters:
  • market_status_function (Callable | None)

  • date_function (Callable)

populateData(force=False)[source]

Fetch and populate dummy ID data.

Parameters:

force (bool) – Force refresh even if data exists

Return type:

None

getDummyID()[source]

Get current dummy ID, updating if necessary.

Return type:

int

Returns:

Current dummy ID

class nepse_client.dummy_id_manager.AsyncDummyIDManager[source]

Bases: _DummyIDManagerBase

Asynchronous dummy ID manager.

Manages dummy IDs for asynchronous NEPSE client, with support for concurrent operations and proper async synchronization.

__init__(market_status_function=None, date_function=<built-in method now of type object>)[source]

Initialize asynchronous dummy ID manager.

Parameters:
  • market_status_function (Callable | None)

  • date_function (Callable)

async populateData(force=False)[source]

Fetch and populate dummy ID data asynchronously.

Ensures only one update operation happens at a time, even with concurrent requests.

Parameters:

force (bool) – Force refresh even if data exists

Return type:

None

async getDummyID()[source]

Get current dummy ID, updating if necessary.

Return type:

int

Returns:

Current dummy ID

exceptions

Custom exceptions for NEPSE Client.

This module provides a comprehensive exception hierarchy for handling various error scenarios when interacting with the NEPSE API.

exception nepse_client.exceptions.NepseError[source]

Bases: Exception

Base exception class for all NEPSE-related errors.

All custom exceptions in this library inherit from this class, allowing for easy catch-all error handling.

message

Human-readable error description

status_code

HTTP status code (if applicable)

response_data

Raw response data from the API

request_data

Original request data

__init__(message, status_code=None, response_data=None, request_data=None)[source]

Initialize NepseError.

Parameters:
  • message (str) – Error description

  • status_code (Optional[int]) – HTTP status code

  • response_data (Optional[Any]) – Response from the API

  • request_data (Optional[dict[str, Any]]) – Original request data

__str__()[source]

Return string representation of the error.

Return type:

str

__repr__()[source]

Return detailed representation of the error.

Return type:

str

to_dict()[source]

Convert exception to dictionary for logging/serialization.

Return type:

dict[str, Any]

Returns:

Dictionary representation of the exception

exception nepse_client.exceptions.NepseClientError[source]

Bases: NepseError

Raised when client sends an invalid request (4xx errors).

This typically indicates: - Invalid parameters - Missing required fields - Malformed request data - Invalid company symbol

Example

>>> try:
...     client.getCompanyDetails("INVALID")
... except NepseClientError as e:
...     print(f"Invalid request: {e}")
__init__(message='Invalid client request', status_code=400, response_data=None, request_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

  • request_data (dict[str, Any] | None)

exception nepse_client.exceptions.NepseAuthenticationError[source]

Bases: NepseError

Raised when access token has expired (401 Unauthorized).

This exception is typically handled automatically by the client, which will refresh the token and retry the request.

Note

Users usually don’t need to handle this exception directly as the client manages token refresh automatically.

__init__(message='Authentication token expired', status_code=401, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

exception nepse_client.exceptions.NepseBadGatewayError[source]

Bases: NepseError

Raised when server returns 502 Bad Gateway.

This typically indicates: - Server temporarily unavailable - Upstream server issues - Network problems between servers

Recommended action: Retry the request after a short delay.

__init__(message='Bad Gateway - Server temporarily unavailable', status_code=502, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

exception nepse_client.exceptions.NepseServerError[source]

Bases: NepseError

Generic server error for 5xx status codes.

This indicates an error on the NEPSE server side. Common causes: - Internal server error (500) - Service unavailable (503) - Gateway timeout (504)

Recommended action: Retry with exponential backoff or contact support.

__init__(message='Server error occurred', status_code=500, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int)

  • response_data (Any | None)

exception nepse_client.exceptions.NepseNetworkError[source]

Bases: NepseError

Raised for general network or unexpected HTTP issues.

This covers: - Connection timeouts - DNS resolution failures - SSL/TLS errors - Unexpected response formats - Network interruptions

Recommended action: Check network connectivity and retry.

__init__(message='Network error occurred', status_code=None, response_data=None)[source]

Initialize the exception with a default message.

Parameters:
  • message (str)

  • status_code (int | None)

  • response_data (Any | None)

exception nepse_client.exceptions.NepseValidationError[source]

Bases: NepseError

Raised when input validation fails before making API request.

This is raised for client-side validation errors such as: - Invalid date formats - Out of range values - Missing required parameters - Invalid data types

Example

>>> try:
...     client.getCompanyPriceVolumeHistory("NABIL", start_date="invalid")
... except NepseValidationError as e:
...     print(f"Validation error: {e}")
__init__(message='Input validation failed', field=None, value=None)[source]

Initialize validation error.

Parameters:
  • message (str) – Error description

  • field (Optional[str]) – Name of the invalid field

  • value (Optional[Any]) – Invalid value provided

exception nepse_client.exceptions.NepseRateLimitError[source]

Bases: NepseError

Raised when API rate limit is exceeded (429 Too Many Requests).

retry_after

Seconds to wait before retrying (if provided by server)

__init__(message='Rate limit exceeded', status_code=429, retry_after=None)[source]

Initialize rate limit error.

Parameters:
  • message (str) – Error description

  • status_code (int) – HTTP status code

  • retry_after (Optional[int]) – Seconds to wait before retry

exception nepse_client.exceptions.NepseDataNotFoundError[source]

Bases: NepseError

Raised when requested data is not found.

This is used when: - Company symbol doesn’t exist - No data available for requested date - Empty result sets

Example

>>> try:
...     client.getFloorSheetOf("INVALID", "2024-01-01")
... except NepseDataNotFoundError as e:
...     print(f"Data not found: {e}")
__init__(message='Requested data not found', resource=None)[source]

Initialize data not found error.

Parameters:
  • message (str) – Error description

  • resource (Optional[str]) – Resource that was not found

exception nepse_client.exceptions.NepseTimeoutError[source]

Bases: NepseError

Raised when request times out.

This occurs when the server doesn’t respond within the specified timeout period.

timeout

Timeout value in seconds

__init__(message='Request timeout', timeout=None)[source]

Initialize timeout error.

Parameters:
  • message (str) – Error description

  • timeout (Optional[float]) – Timeout value in seconds

exception nepse_client.exceptions.NepseConnectionError[source]

Bases: NepseError

Raised when connection to NEPSE server fails.

This is different from NepseNetworkError as it specifically indicates inability to establish a connection.

__init__(message='Failed to connect to NEPSE server')[source]

Initialize the exception with a default message.

Parameters:

message (str)

exception nepse_client.exceptions.NepseConfigurationError[source]

Bases: NepseError

Raised when there’s an issue with client configuration.

This includes: - Missing required configuration files - Invalid configuration values - Corrupted data files

__init__(message='Configuration error')[source]

Initialize the exception with a default message.

Parameters:

message (str)

nepse_client.exceptions.get_exception_for_status(status_code, message, response_data=None)[source]

Get appropriate exception class for HTTP status code.

Parameters:
  • status_code (int) – HTTP status code

  • message (str) – Error message

  • response_data (Optional[Any]) – Response data from API

Return type:

NepseError

Returns:

Appropriate exception instance