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:
_NepseBaseSynchronous 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 instancemask_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)
- 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 symbolstart_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 downloadpaginated (
bool) – Return list of pages instead of flattened listpage (
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 symbolbusiness_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)
- 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 URLinclude_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 URLpayload_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:
_NepseBaseAsynchronous 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 instancemask_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)
- 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 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 getMarketStatus()[source]
Get current market status (open/closed).
- Return type:
dict[str,Any]
- 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 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 getSymbolMarketDepth(symbol)[source]
Get market depth for a symbol.
- Return type:
dict[str,Any]- Parameters:
symbol (str)
- 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 URLinclude_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 URLpayload_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:
ExceptionBase 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 descriptionstatus_code (
Optional[int]) – HTTP status coderesponse_data (
Optional[Any]) – Response from the APIrequest_data (
Optional[dict[str,Any]]) – Original request data
- exception nepse_client.NepseClientError[source]
Bases:
NepseErrorRaised 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}")
- exception nepse_client.NepseServerError[source]
Bases:
NepseErrorGeneric 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.
- exception nepse_client.NepseAuthenticationError[source]
Bases:
NepseErrorRaised 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.
- exception nepse_client.NepseNetworkError[source]
Bases:
NepseErrorRaised 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.
- exception nepse_client.NepseValidationError[source]
Bases:
NepseErrorRaised 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}")
- exception nepse_client.NepseBadGatewayError[source]
Bases:
NepseErrorRaised 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.
- exception nepse_client.NepseRateLimitError[source]
Bases:
NepseErrorRaised when API rate limit is exceeded (429 Too Many Requests).
- retry_after
Seconds to wait before retrying (if provided by server)
- exception nepse_client.NepseDataNotFoundError[source]
Bases:
NepseErrorRaised 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}")
- exception nepse_client.NepseTimeoutError[source]
Bases:
NepseErrorRaised when request times out.
This occurs when the server doesn’t respond within the specified timeout period.
- timeout
Timeout value in seconds
- exception nepse_client.NepseConnectionError[source]
Bases:
NepseErrorRaised when connection to NEPSE server fails.
This is different from NepseNetworkError as it specifically indicates inability to establish a connection.
- exception nepse_client.NepseConfigurationError[source]
Bases:
NepseErrorRaised when there’s an issue with client configuration.
This includes: - Missing required configuration files - Invalid configuration values - Corrupted data files
Main Classes
NepseClient
- class nepse_client.NepseClient[source]
Bases:
_NepseBaseSynchronous 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 instancemask_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
- requestGETAPI(url, include_authorization_headers=True)[source]
Make GET request to NEPSE API.
- Parameters:
url (
str) – API endpoint URLinclude_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 URLpayload_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
- 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 symbolstart_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 downloadpaginated (
bool) – Return list of pages instead of flattened listpage (
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 symbolbusiness_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:
_NepseBaseAsynchronous 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 instancemask_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 requestGETAPI(url, include_authorization_headers=True)[source]
Make async GET request to NEPSE API.
- Parameters:
url (
str) – API endpoint URLinclude_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 URLpayload_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 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 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)
- 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 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’.
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 datakeys (
tuple) – Tuple of keys to mask
- Return type:
dict[str,Any]- Returns:
Dictionary with masked sensitive values
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:
_NepseBaseSynchronous 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 instancemask_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
- requestGETAPI(url, include_authorization_headers=True)[source]
Make GET request to NEPSE API.
- Parameters:
url (
str) – API endpoint URLinclude_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 URLpayload_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
- 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 symbolstart_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 downloadpaginated (
bool) – Return list of pages instead of flattened listpage (
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 symbolbusiness_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:
_NepseBaseAsynchronous 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 instancemask_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 requestGETAPI(url, include_authorization_headers=True)[source]
Make async GET request to NEPSE API.
- Parameters:
url (
str) – API endpoint URLinclude_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 URLpayload_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 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 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)
- 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 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:
_TokenManagerBaseSynchronous token manager.
Manages authentication tokens for synchronous NEPSE client, automatically refreshing tokens when they expire.
- getAccessToken()[source]
Get valid access token, refreshing if necessary.
- Return type:
str- Returns:
Valid access token
- class nepse_client.token_manager.AsyncTokenManager[source]
Bases:
_TokenManagerBaseAsynchronous token manager.
Manages authentication tokens for asynchronous NEPSE client, with support for concurrent token refresh operations.
- async getAccessToken()[source]
Get valid access token, refreshing if necessary.
- Return type:
str- Returns:
Valid access 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:
_DummyIDManagerBaseSynchronous 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)
- class nepse_client.dummy_id_manager.AsyncDummyIDManager[source]
Bases:
_DummyIDManagerBaseAsynchronous 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)
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:
ExceptionBase 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 descriptionstatus_code (
Optional[int]) – HTTP status coderesponse_data (
Optional[Any]) – Response from the APIrequest_data (
Optional[dict[str,Any]]) – Original request data
- exception nepse_client.exceptions.NepseClientError[source]
Bases:
NepseErrorRaised 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}")
- exception nepse_client.exceptions.NepseAuthenticationError[source]
Bases:
NepseErrorRaised 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.
- exception nepse_client.exceptions.NepseBadGatewayError[source]
Bases:
NepseErrorRaised 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.
- exception nepse_client.exceptions.NepseServerError[source]
Bases:
NepseErrorGeneric 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.
- exception nepse_client.exceptions.NepseNetworkError[source]
Bases:
NepseErrorRaised 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.
- exception nepse_client.exceptions.NepseValidationError[source]
Bases:
NepseErrorRaised 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}")
- exception nepse_client.exceptions.NepseRateLimitError[source]
Bases:
NepseErrorRaised when API rate limit is exceeded (429 Too Many Requests).
- retry_after
Seconds to wait before retrying (if provided by server)
- exception nepse_client.exceptions.NepseDataNotFoundError[source]
Bases:
NepseErrorRaised 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}")
- exception nepse_client.exceptions.NepseTimeoutError[source]
Bases:
NepseErrorRaised when request times out.
This occurs when the server doesn’t respond within the specified timeout period.
- timeout
Timeout value in seconds
- exception nepse_client.exceptions.NepseConnectionError[source]
Bases:
NepseErrorRaised when connection to NEPSE server fails.
This is different from NepseNetworkError as it specifically indicates inability to establish a connection.
- exception nepse_client.exceptions.NepseConfigurationError[source]
Bases:
NepseErrorRaised when there’s an issue with client configuration.
This includes: - Missing required configuration files - Invalid configuration values - Corrupted data files
- 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 codemessage (
str) – Error messageresponse_data (
Optional[Any]) – Response data from API
- Return type:
- Returns:
Appropriate exception instance