Usage¶
Installation¶
To use bse, first install it using pip:
$ pip install bse
Example¶
from bse import BSE
bse = BSE()
bse.exit() # close requests session
with BSE() as bse:
pass
API¶
- class bse.BSE(download_folder: str | Path)¶
Unofficial Python Api for BSE India
- Parameters:
download_folder (pathlib.Path or str) – A folder/dir to save downloaded files and cookie files
- Raises:
ValueError – if
download_folderis not a folder/dir
General Methods¶
- BSE.exit()¶
Close the Request session
- BSE.lookup(text: str) dict | None¶
Added in version 3.1.0.
Search by Company name, stock symbol, ISIN or BSE code.
- Parameters:
text (str) – A string representing the Company name, Stock symbol, ISIN code or BSE code.
- Returns:
None if lookup failed else a dictionary containing company_name, symbol, isin and bse_code. Sample response
- Return type:
Optional[dict]
- BSE.getScripName(scripcode) str¶
Get stock symbol name for BSE scrip code
- Parameters:
scripcode – BSE scrip code
- Raises:
ValueError – if scrip not found
TimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
Symbol code
- Return type:
str
Example 500180 -> ‘HDFCBANK’
- BSE.getScripCode(scripname)¶
Get BSE scrip code for stock symbol name
- Parameters:
scripname – Stock symbol code
- Raises:
ValueError – if scrip not found
TimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
BSE scrip code
- Return type:
str
Example HDFCBANK -> ‘500180’
Download Reports¶
- BSE.bhavcopyReport(date: datetime, folder: str | Path | None = None)¶
Download the daily bhavcopy report for specified
date- Parameters:
date (datetime.datetime) – date of report
folder (str or pathlib.Path or None) – Optional dir/folder to save the file to
- Raises:
ValueError – if
folderis not a dir/folder.RuntimeError – if report is unavailable or not yet updated.
FileNotFoundError – if file download failed or file is corrupt.
TimeoutError – if request timed out with no response
- Returns:
file path of downloaded report
- Return type:
pathlib.Path
- BSE.deliveryReport(date: datetime, folder: str | Path | None = None)¶
Download the daily delivery report for specified
date- Parameters:
date (datetime.datetime) – date of report
folder (str or pathlib.Path or None) – Optional dir/folder to save the file to
- Raises:
ValueError – if
folderis not a dir/folder.RuntimeError – if report is unavailable or not yet updated.
FileNotFoundError – if file download failed or file is corrupt.
TimeoutError – if request timed out with no response
- Returns:
file path of downloaded report
- Return type:
pathlib.Path
Zip file is extracted, converted to CSV, and saved filepath is returned
- BSE.fetchHistoricalIndexData(index: str, from_date: date, to_date: date, period: Literal['D', 'M', 'Y'] = 'D', folder: str | Path | None = None) Path | None¶
Download historical data for the specified index for the given date range.
The data for the entire date range is downloaded as a CSV file and the filepath is returned.
If the file is empty, None is returned.
For a list of valid index names, use
fetchIndexNames().To download all index data for the data see
fetchAllIndicesDataByDate()- Parameters:
from_date (datetime.date) – The starting date of the range.
to_date (datetime.date) – The ending date of the range.
index (str) – The index to retrieve data for.
period (Literal["D", "M", "Y"]) – Aggregation period. “D” for daily, “M” for monthly, “Y” for yearly. Defaults to “D”.
folder (str or pathlib.Path or None) – Optional dir/folder to save the file to
- Returns:
None if file is empty else filepath of the downloaded file.
- Return type:
Optional[pathlib.Path]
- Raises:
ValueError – if from_date is greater than to_date
Corporate Filings¶
- BSE.announcements(page_no: int = 1, from_date: datetime | None = None, to_date: datetime | None = None, segment: Literal['equity', 'debt', 'mf_etf'] = 'equity', scripcode: str | None = None, category: str = '-1', subcategory: str = '-1') Dict[str, List[dict]]¶
All corporate announcements
- Parameters:
from_date (datetime.datetime or None) – (Optional) From date.
to_date (datetime.datetime or None) – (Optional) To date.
segment (str) – Default
equity. One ofequity,debtormf_etf.category (str) – (Optional) Filter announcements by category ex.
Corp. Actionsubcategory (str) – (Optional). Filter announcements by subcategory ex.
Dividend.
- Raises:
ValueError – if
from_dateis greater thanto_dateorsubcategoryargument is passed withoutcategoryTimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
All announcements. Sample response
- Return type:
dict[str, list[dict]]
Response is a dictionary containing
TableandTable1keys.Response is paginated. Increment the
page_noon every call, to get all announcements.Tableis a list of dictionary announcements.data['Table1'][0]['ROWCNT']is an integer total of all announcements. Use this info, to incrementpage_no
With no arguments, returns all announcements for current day and time by
page_no.Note
In most cases, it is faster and more bandwidth efficient to lookup by
scripcode. Unless you specifically need to download all announcements. On a typical day, BSE could have 50+ pages and 2K+ announcements.Provide
from_dateandto_dateto return announcements in date range. If not provided, the current date and time is considered.Provide
scripcodeto return announcements for the specified stock.Provide
categoryand orsubcategoryto filter announcements.subcategoryis specific tocategory.categoryis required ifsubcategoryis passed.
Available Constants:
segment:
bse.constants.SEGMENTcategory:
bse.constants.CATEGORY
- BSE.actions(segment: Literal['equity', 'debt', 'mf_etf'] = 'equity', from_date: datetime | None = None, to_date: datetime | None = None, by_date: Literal['ex', 'record', 'bc_start'] = 'ex', scripcode: str | None = None, sector: str = '', purpose_code: str | None = None) List[dict]¶
All forthcoming corporate actions
- Parameters:
segment (str) – Default
equity. One ofequity,debtormf_etf.from_date (datetime.datetime) – (Optional). From date. Defaults to
datetime.datetime.now()to_date (datetime.datetime) – (Optional). To date. Defaults to
datetime.datetime.now()by_date (str) – Default
ex. One ofex,record,bc_startscripcode (str) – (Optional) Limit result to stock symbol
sector (str) – (Optional) Limit results to stocks from sector.
purpose_code (str) – Limit result to actions with given purpose
- Raises:
ValueError – if
from_dateis greater thanto_dateTimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
List of actions. Sample response
- Return type:
list[dict]
With no arguments, returns all forthcoming corp. actions.
Provide
from_dateandto_dateto return corp. actions in date rangeBy default, actions are returned by Ex date. To change this, specify
by_dateasrecord(record date) orbc_start(book closure start date)Provide
scripcodeto return actions for the specified stock.Provide
sectorto limit results to stocks in given sector.Provide
purpose_codeto limit actions to given purpose ex.P5for bonus. Usebse.constants.PURPOSEto pass argument.Available Constants:
sector:
bse.constants.SECTORpurpose_code:
bse.constants.PURPOSE
- BSE.resultCalendar(from_date: datetime | None = None, to_date: datetime | None = None, scripcode: str | None = None) List[dict]¶
Corporate result calendar
- Parameters:
from_date (datetime.datetime) – (Optional). From date.
to_date (datetime.datetime) – (Optional). To date
scripcode (str) – (Optional). Limit result to stock symbol
- Raises:
ValueError – if
from_dateis greater thanto_dateTimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
List of Corporate results. Sample response
- Return type:
list[dict]
With no parameters, returns all forthcoming result dates.
Provide
from_dateandto_dateto filter by date range.Provide
scripcodeto filter by stock.
Market Updates and Summary¶
- BSE.gainers(by: Literal['group', 'index', 'all'] = 'group', name: str | None = None, pct_change: Literal['all', '10', '5', '2', '0'] = 'all') List[dict]¶
List of top gainers
- Parameters:
by (str) – Default
group. One ofgroup,indexorall.name (str) – (Optional). Stock group name or Market index name.
pct_change (str) – Default
all. Filter stocks by percent change. One of10,5,2,0.
- Raises:
ValueError – if
nameis not a valid BSE stock group.TimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
List of top gainers by percent change. Sample response
- Return type:
list[dict]
When
byisgroup,namedefaults to BSE stock groupA.When
byisindex,namedefaults to market indexS&P BSE SENSEX.When
byisall,nameis ignored.By default, all stocks are returned. If
pct_changeis provided, stocks are filtered by range of percent change.10: greater than 10%5: 5% to 10%2: 2% to 5%0: upto 2%
Available Constants:
name:
bse.constants.INDEX. Only ifbyis set toindex
- BSE.losers(by: Literal['group', 'index', 'all'] = 'group', name: str | None = None, pct_change: Literal['all', '10', '5', '2', '0'] = 'all') List[dict]¶
List of top losers
- Parameters:
by (str) – Default
group. One ofgroup,indexorall.name (str) – (Optional). Stock group name or Market index name.
pct_change (str) – Default
all. Filter stocks by percent change. One of10,5,2,0.
- Raises:
ValueError – if
nameis not a valid BSE stock group.TimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
List of top losers by percent change. Sample response
- Return type:
list[dict]
When
byisgroup,namedefaults to BSE stock groupA.When
byisindex,namedefaults to market indexS&P BSE SENSEX.When
byisall,nameis ignored.By default, all stocks are returned. If
pct_changeis provided, stocks are filtered by range of percent change.10: less than -10%5: -5% to -10%2: -2% to -5%0: upto -2%
Available Constants:
name:
bse.constants.INDEX. Only ifbyis set toindex
- BSE.near52WeekHighLow(by: Literal['group', 'index', 'all'] = 'group', name: str | None = None) Dict[str, List[dict]]¶
Get stocks near 52 week highs and lows
- Parameters:
by (str) – Default
group. One ofgroup,indexorall.name (str) – (Optional). Stock group name or Market index name.
- Raises:
ValueError – if
nameis not a valid BSE stock group.TimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
Stocks near 52 week high and lows. Sample response
- Return type:
dict
When
byisgroup,namedefaults to BSE stock groupA.When
byisindex,namedefaults to market indexS&P BSE SENSEX.When
byisall,nameis ignored.
The result is a dictionary with keys
highandlow.highis a list of dictionary containing stocks near 52 week high.lowis a list of dictionary containing stocks near 52 week low.
Available Constants:
name:
bse.constants.INDEX. Only ifbyis set toindex
- BSE.quote(scripcode) Dict[str, float]¶
Get OHLC quotes for given scripcode
- Parameters:
scripcode (str) – BSE scrip code
- Raises:
TimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
OHLC data for given scripcode. Sample response
- Return type:
dict[str, float]
- BSE.quoteWeeklyHL(scripcode) dict¶
Get 52 week and monthly high & low data for given stock.
- Parameters:
scripcode (str) – BSE scrip code
- Raises:
TimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
Weekly and monthly high and lows with dates. Sample response
- Return type:
dict
- BSE.listSecurities(industry: str = '', scripcode: str = '', group: str = 'A', segment: str = 'Equity', status: str = 'Active') List[dict]¶
List securities and their meta info like symbol code, ISIN code, industry, market cap, segment, group etc.
Note
The default parameters will list Group ‘A’ in the ‘equity’ segment with an ‘active’ status.
- Parameters:
industry (str) – (Optional) Filter by industry name
scripcode (str) – (Optional) BSE scrip code
group (str) – Default ‘A’. BSE stock group
segment – Default ‘Equity’. One of
equity,mf,Preference Shares,Debentures and Bonds,Equity - Institutional Series,Commercial Papersstatus – Default ‘Active’. One of
active,suspended, ordelisted
- Raises:
ValueError – if
groupis not a valid BSE stock groupTimeoutError – if request timed out with no response
ConnectionError – in case of HTTP error or server returns error response.
- Returns:
list of securities with meta info. Sample response
- Return type:
list[dict]
With no arguments, returns all active A group equity stocks
Available Constants:
industry:
bse.constants.INDUSTRYsegment:
bse.constants.SEGMENTstatus:
bse.constants.STATUS
- BSE.fetchAllIndicesDataByDate(dt: date) Dict[str, List[Dict]]¶
Fetch daily data for all indices for a given date.
To download historical index data for a specific index by date range, see meth:.fetchHistoricalIndexData
- Parameters:
dt (datetime.date) – The date for which to fetch index data.
- Returns:
A dictionary where each key is an index name, and each value is a list of dictionaries containing index data.
- Return type:
Dict[str, List[Dict]]
- BSE.fetchIndexNames() Dict[str, List[Dict]]¶
Fetch the list of Indices to be used in conjunction with
fetchHistoricalIndexData().Reference: https://www.bseindia.com/indices/IndexArchiveData.html
- BSE.fetchIndexReportMetadata() Dict[str, List[Dict]]¶
Returns a dictionary with a Table key containing a list of dict.
The dictionary contains metadata about AllIndices report along with the last updated date.
Useful to check if the Index data for the latest trading session has been updated.
Used in conjunction with
fetchHistoricalIndexData()Reference: https://www.bseindia.com/indices/IndexArchiveData.html