BharatFinTrack Module
- class BharatFinTrack.Analyzer[source]
Bases:
objectProvide functionality for analyzing data.
- correction_recovery_cycles(csv_file: str, excel_file: str, minimum_gain: int | float = 10, mult_correction: int | float = 2.5, mult_recovery: int | float = 10) DataFrame[source]
Identify significant turning points in the security’s historical performance, focusing on consecutive corrections and recoveries. A minimum percentage gain is required between two consecutive recoveries to qualify as significant. The function also calculates the frequency of corrections (declines from a peak to the next trough) and recoveries (gains from a trough to the next peak), applying specified multipliers to filter the movements. The output offers a comprehensive overview of the security’s behavior over time.
- Parameters:
csv_file (str) – Path to the CSV file obtained from
BharatFinTrack.NSETRI.download_daily_data().excel_file (str) – Path to an Excel file to save the output DataFrame.
minimum_gain (float, optional) – The minimum percentage gain required between two consecutive tops. Default is 10.
mult_correction (float, optional) – Multiplier applied to calculate the magnitude of corrections (top to bottom). Default is 2.5.
mult_recovery (float, optional) – Multiplier applied to calculate the magnitude of recoveries (bottom to top). Default is 10.
- Returns:
DataFrame containing the analysis results, with columns indicating identified tops, bottoms, corrections, recoveries, and their respective multipliers.
- Return type:
DataFrame
- extract_data_between_dates(input_csv: str, start_date: str, end_date: str, output_csv: str | None = None) DataFrame[source]
Extract historical daily closing values from downloaded data between the given start and end dates, both inclusive.
- Parameters:
input_csv (str) – Path to the CSV file generated by
BharatFinTrack.NSETRI.download_daily_data().start_date (str) – Start date in the format ‘DD-MMM-YYYY’.
end_date (str) – End date in the format ‘DD-MMM-YYYY’.
output_csv (str) – Path to the CSV file where the filtered data will be saved.
- Returns:
DataFrame containing the daily closing values between the specified dates.
- Return type:
DataFrame
- sort_equity_index_close(csv_file: str, excel_file: str) DataFrame[source]
Sort the DataFrame in descending order by equity index closing values.
- Parameters:
csv_file (str) – Path to the input CSV file generated by either
BharatFinTrack.NSETRI.download_equity_close()orBharatFinTrack.NSEPRI.download_equity_close().excel_file (str) – Path to an Excel file to save the output DataFrame.
- Returns:
DataFrame sorted in descending order based on the index closing value column.
- Return type:
DataFrame
- class BharatFinTrack.CAGR[source]
Bases:
objectProvide functionalities for computing and analyzing Compound Annual Growth Rate (CAGR).
- compare_performance(indices: list[str], dir_path: str, excel_file: str) DataFrame[source]
Generate two DataFrames that compare year-wise CAGR (%) and growth multiple (X) of a yearly fixed investment across multiple securities. Here, year-wise refers to the CAGR calculated for periods ending on the present date, going back one year, two years, and so on, up to the available data range. The output DataFrames are saved to an Excel file, where the cells with the best performance among securities for each year are highlighted in green-yellow, and those with the worst performance are highlighted in sandy brown.
Additionally, a scoring mechanism is implemented for the securities based on their growth values. For each year, securities are ranked in ascending order of growth, with the lowest value receiving the lowest score (1), and the highest value receiving the highest score. The total scores for each security are calculated by summing their yearly scores. Securities are then sorted in descending order based on their total scores.
- Parameters:
indices (list) – A list of index (security) names to compare in the CAGR (%) and growth multiple (X).
dir_path (str) – Path to the directory containing CSV files with historical data for each index. Each CSV file must be named as
{index}.csvcorresponding to the index names provided in theindiceslist. These files should be obtained fromBharatFinTrack.NSETRI.download_daily_data()andBharatFinTrack.NSETRI.update_daily_data()methods.excel_file (str) – Path to an Excel file to save the output DataFrames.
- Returns:
DataFrame containing the index names and their total scores.
- Return type:
DataFrame
- sort_since_inception(csv_file: str, within_category: bool = False, excel_file: str | None = None) DataFrame[source]
Sort securities in descending order by CAGR (%) since inception, either across all securities or within each category.
- Parameters:
csv_file (str) – Path to the input CSV file generated by either
BharatFinTrack.NSETRI.download_equity_close()orBharatFinTrack.NSEPRI.download_equity_close().within_category (bool, optional) – If True, sort securities within each category; otherwise, sort across all securities. Default is False.
excel_file (str, optional) – Path to an Excel file to save the output DataFrame. Default is None.
- Returns:
DataFrame sorted in descending order by CAGR (%) since launch.
- Return type:
DataFrame
- yearly_return(csv_file: str, excel_file: str | None = None) DataFrame[source]
Calculate the year-wise CAGR (%) for a given security. Here, year-wise refers to the CAGR calculated for periods ending on the present date, going back one year, two years, three years, and so on, up to the available data range.
- Parameters:
csv_file (str) – Path to the CSV file obtained from
BharatFinTrack.NSETRI.download_daily_data().excel_file (str, optional) – Path to an Excel file to save the output DataFrame. Default is None.
- Returns:
DataFrame containing the yearly CAGR (%).
- Return type:
DataFrame
- class BharatFinTrack.NSEPRI[source]
Bases:
objectProvide functionalities to download and analyze NSE Price Return Index (PRI), excluding dividend reinvestment.
- download_equity_close(csv_file: str, http_headers: dict[str, str] | None = None, untracked_base_equity: bool = False) DataFrame[source]
Download closing values for all equity indices.
- Parameters:
csv_file (str) – Path to a CSV file to save the DataFrame.
http_headers (dict, optional) – HTTP header dictionary used for the web request. If the default header is not suitable for the user’s environment, a custom header must be provided. The header must include the key
content-typewith valueapplication/json; charset=UTF-8.untracked_base_equity (bool, optional) – If True, print equity indices present in the downloaded data but missing from the in-built base file. Default is False.
- Returns:
DataFrame containing closing values for all equity indices.
- Return type:
DataFrame
- class BharatFinTrack.NSEProduct[source]
Bases:
objectProvides functionality for accessing the characteristics of NSE related financial products.
- equity_base_parameter_midf(excel_file: str) DataFrame[source]
Generate a MultiIndex DataFrame containing the base parameters of equity indices and save it to an Excel file.
- Parameters:
excel_file (str) – Path to the Excel file where the DataFrame will be saved.
- Returns:
A MultiIndex DataFrame containing the base parameters (identifier, start date, and base value) of the available equity indices.
- Return type:
DataFrame
- equity_categorical_indices(category: str) list[str][source]
Return the equity index identifiers for a specified category.
- Parameters:
category (str) – Equity index category. Must be one of:
broad,sector,thematic, orstrategy.- Returns:
List of equity index identifiers corresponding to the specified category.
- Return type:
list
- class BharatFinTrack.NSETRI[source]
Bases:
objectProvide functionality for downloading NSE Equity Total Return Index (TRI) data, including both price and dividend reinvestment.
- download_daily_data(index: str, start_date: str | None = None, end_date: str | None = None, http_headers: dict[str, str] | None = None, csv_file: str | None = None) DataFrame[source]
Download historical daily closing values for the specified index between the given start and end dates (both inclusive).
- Parameters:
index (str) – Name of the index identifier.
start_date (str, optional) – Start date in the format ‘DD-MMM-YYYY’. If None, defaults to the index base date.
end_date (str, optional) – End date in the format ‘DD-MMM-YYYY’. If None, defaults to the current date.
http_headers (dict, optional) – HTTP header dictionary used for the web request. If the default header is not suitable for the user’s environment, a custom header must be provided. The header must include the key
content-typewith valueapplication/json; charset=UTF-8.csv_file (str, optional) – File path where the resulting DataFrame will be saved as a CSV file.
- Returns:
DataFrame containing the daily dates and corresponding closing values for the index within the specified date range.
- Return type:
DataFrame
- download_equity_close(csv_file: str, http_headers: dict[str, str] | None = None, test_mode: bool = False) DataFrame[source]
Download closing values for all equity indices.
- Parameters:
csv_file (str) – Path to a CSV file to save the DataFrame.
http_headers (dict, optional) – HTTP header dictionary used for the web request. If the default header is not suitable for the user’s environment, a custom header must be provided. The header must include the key
content-typewith valueapplication/json; charset=UTF-8.test_mode (bool, optional) – If True, the function will use a mocked DataFrame for testing purposes instead of the actual data. This parameter is intended for developers for testing purposes only and is not recommended for use by end-users. Default is False.
- Returns:
DataFrame containing closing values for all equity indices.
- Return type:
DataFrame
- update_daily_data(index: str, csv_file: str, http_headers: dict[str, str] | None = None) DataFrame[source]
Update historical daily closing values from the last date in the input CSV file to the current and save the aggregated data to the same file.
- Parameters:
index (str) – Name of the index identifier.
csv_file (str) – Path to the CSV file generated by
BharatFinTrack.NSETRI.download_daily_data().http_headers (dict, optional) – HTTP header dictionary used for the web request. If the default header is not suitable for the user’s environment, a custom header must be provided. The header must include the key
content-typewith valueapplication/json; charset=UTF-8.
- Returns:
A DataFrame containing daily closing values from the last recorded date to the current date.
- Return type:
DataFrame
- class BharatFinTrack.SIP[source]
Bases:
objectProvide functionalities for computing and analyzing Systematic Investment Plan (SIP).
- compare_performance(indices: list[str], dir_path: str, excel_file: str) DataFrame[source]
Generate two DataFrames that compares year-wise XIRR (%) and growth multiple (X) on the first date SIP investment of each month across multiple securities. The output DataFrame are saved to an Excel file, where the cells with the best performance among securities for each year are highlighted in green-yellow, and those with the worst performance are highlighted in sandy brown.
Additionally, a scoring mechanism is implemented for the securities based on their growth values. For each year, indices are ranked in ascending order of growth, with the lowest value receiving the lowest score (1), and the highest value receiving the highest score. The total scores for each security are calculated by summing their yearly scores. Securities are then sorted in descending order based on their total scores.
- Parameters:
indices (list) – A list of index (security) names to compare in the monthly SIP XIRR (%) and growth multiple (X).
dir_path (str) – Path to the directory containing CSV files with historical data for each index. Each CSV file must be named as
{index}.csvcorresponding to the index names provided in theindiceslist. These files should be obtained fromBharatFinTrack.NSETRI.download_daily_data()andBharatFinTrack.NSETRI.update_daily_data()methods.excel_file (str) – Path to an Excel file to save the output DataFrames.
- Returns:
DataFrame containing the index names and their total scores.
- Return type:
DataFrame
- growth_from_given_date(csv_file: str, yr_mon: tuple[int, int] | None = None, invest: int = 1000) Series[source]
Compute the closing value, growth multiple, and annualized XIRR (%) of a fixed monthly SIP starting from a specified date, assuming investments are made on the first available trading date of each month.
- Parameters:
csv_file (str) – Path to the CSV file obtained from
BharatFinTrack.NSETRI.download_daily_data().yr_mon (tuple, optional) – Tuple containing the year and month (1–12), respectively, from which the SIP investment begins.
invest (int, optional) – Fixed investment amount contributed on the first date of each month. Default is 1000.
- Returns:
Series containing the closing value, growth multiple, and annualized XIRR (%) for the SIP investment starting from the specified date.
- Return type:
Series
- investment_growth(invest: int, frequency: str, annual_return: int | float, years: int, excel_file: str | None = None) DataFrame[source]
Calculate the SIP growth over a specified number of years for a fixed investment amount.
- Parameters:
invest (int) – Fixed amount invested at each SIP interval.
frequency (str) – Frequency of SIP contributions; must be one of
yearly,quarterly,monthly, andweekly.annual_return (float) – Expected annual return rate in percentage.
years (int) – Total number of years for the SIP investment duration.
excel_file (str, optional) – Path to an Excel file to save the output DataFrame. Default is None.
- Returns:
A DataFrame containing columns for the annual investment, closing balance, and cumulative growth over the investment period.
- Return type:
DataFrame
- yearly_return(csv_file: str, invest: int = 1000, excel_file: str | None = None) DataFrame[source]
Compute the year-wise closing value, growth multiples, and annualized XIRR (%) of a fixed monthly SIP tracking a security, assuming investments are made on the first available trading date of each month.
- Parameters:
csv_file (str) – Path to the CSV file obtained from
BharatFinTrack.NSETRI.download_daily_data().invest (int) – Fixed investment amount contributed on the first date of each month.
excel_file (str, optional) – Path to an Excel file to save the output DataFrame. Default is None.
- Returns:
DataFrame containing the year-wise closing value, growth multiples, and annualized XIRR (%) for the fixed monthly SIP investment.
- Return type:
DataFrame
- class BharatFinTrack.Visual[source]
Bases:
objectProvides functionality for visualizing data.
- cagr_leaders(excel_file: str, figure_file: str, number_leader: int = 15, fig_width: int | float = 15, fig_height: int | float = 10, fig_title: str | None = None, fig_ylabel: str | None = None, gui_window: bool = True) Figure[source]
Generate a bar plot of top-performing securities by CAGR (%) since launch.
- Parameters:
excel_file (str) – Path to the input Excel file generated by
BharatFinTrack.CAGR.sort_since_inception()withwithin_category=False.figure_file (str) – File Path to save the output figure.
number_leader (int, optional) – Number of top indices to display based on CAGR (%). Default is 15.
fig_width (float, optional) – Width of the figure in inches. Default is 15.
fig_height (float, optional) – Height of the figure in inches. Default is 10.
fig_title (str, optional) – Title of the figure. Default is None.
fig_ylabel (str, optional) – Label for the y-axis.. Default is None.
gui_window (bool, optional) – If True (default), open a graphical user interface window for the plot.
- Returns:
Bar plot showing the top CAGR (%) securities.
- Return type:
Figure
- cagr_leaders_by_category(excel_file: str, figure_file: str, number_leader: int = 5, fig_width: int | float = 15, fig_height: int | float = 10, fig_title: str | None = None, fig_ylabel: str | None = None, gui_window: bool = True) Figure[source]
Generate a bar plot of top-performing securities by CAGR (%) within each category since launch.
- Parameters:
excel_file (str) – Path to the input Excel file generated by
BharatFinTrack.CAGR.sort_since_inception()withwithin_category=True.figure_file (str) – File Path to save the output figure.
number_leader (int, optional) – Number of top indices to display per category based on CAGR (%). Default is 5.
fig_width (float, optional) – Width of the figure in inches. Default is 15.
fig_height (float, optional) – Height of the figure in inches. Default is 10.
fig_title (str, optional) – Title of the figure. Default is None.
fig_ylabel (str, optional) – Label for the y-axis.. Default is None.
gui_window (bool, optional) – If True (default), open a graphical user interface window for the plot.
- Returns:
Bar plot showing the top CAGR (%) securities within each category.
- Return type:
Figure
- compare_performance(excel_file: str, figure_file: str, fig_width: int | float = 15, fig_height: int | float = 10, fig_title: str | None = None, ytick_gap: int = 2, gui_window: bool = True) Figure[source]
Generate a line plot comparing growth multiple of investment across multiple securities over the years.
- Parameters:
excel_file (str) – Path to the input Excel file generated by either
BharatFinTrack.SIP.compare_performance()orBharatFinTrack.CAGR.compare_performance().figure_file (str) – File Path to save the output figure.
fig_width (float, optional) – Width of the figure in inches. Default is 15.
fig_height (float, optional) – Height of the figure in inches. Default is 10.
fig_title (str, optional) – Title of the figure. Default is None.
ytick_gap (int, optional) – Gap between two y-axis ticks. Default is 200.
gui_window (bool, optional) – If True (default), open a graphical user interface window for the plot.
- Returns:
Line plot comparing growth multiple of investment across multiple securities over the years.
- Return type:
Figure
- compare_sip_to_bond_benchmark(excel_file: str, figure_file: str, bond_yield: int | float = 7, fig_width: int | float = 15, fig_height: int | float = 10, fig_title: str | None = None, ytick_gap: int = 200, gui_window: bool = True, asset_legend: str = 'Index growth') Figure[source]
Generate a bar plot comparing the SIP value of a specified security against government bond over time, assuming a monthly investment of 1 Rupee.
- Parameters:
excel_file (str) – Path to the input Excel file generated by
BharatFinTrack.SIP.yearly_return().figure_file (str) – File Path to save the output figure.
bond_yield (float, optional) – Expected annual yield (%) of government securities. Default is 7.
fig_width (float, optional) – Width of the figure in inches. Default is 15.
fig_height (float, optional) – Height of the figure in inches. Default is 10.
fig_title (str, optional) – Title of the figure. Default is None.
ytick_gap (int, optional) – Gap between two y-axis ticks. Default is 200.
gui_window (bool, optional) – If True (default), open a graphical user interface window for the plot.
asset_legend (str, optional) – Label used for the asset in the plot legend. Default is ‘Index growth’.
- Returns:
Bar plot comparing SIP values of the security and government bond over time.
- Return type:
Figure