🇮🇳 bfinance (Bharat Finance)
The High-Performance Python SDK for Indian Equities (NSE & BSE)
An Indian-equity alternative to yfinance implementing a measured subset of its 1.7.0 Ticker API, supercharged with 10-year audited Ind AS financials, concalls with streamable audio MP3s, institutional stock screeners, multi-tab Excel models, and native AI/LLM data feeds.
🚀 Why bfinance?
Standard financial libraries like yfinance often fail Indian equity investors: Yahoo Finance truncates Indian financial statements to just 4–5 years, frequently experiences missing fundamental data, lacks conference calls and shareholding patterns, and breaks with upstream API changes.
bfinance solves this for Indian equities. It implements a measured subset of the yfinance 1.7.0 Ticker API — 44 of 98 members carry a real data path, 14 are present-but-empty, and 40 are refused by name — so a migrating caller knows exactly what moves without a code change and what does not, while getting access to deep Indian corporate data. The measured table and the concrete breaks are in docs/YFINANCE_PARITY.md:
| Dimension | yfinance (Standard) |
bfinance (Supercharged) |
|---|---|---|
| API Syntax | 1.7.0+ Standard | Measured subset — 44 present, 14 present-but-empty, 40 refused (docs/YFINANCE_PARITY.md); not a 100% drop-in |
| Financial Statements Depth | 4 to 5 Years (Standard Yahoo) | 10 to 13+ Years (Audited Ind AS Statements) |
| Quarterly Statement History | 4 to 5 Quarters | 12 to 16+ Historical Quarters |
| Institutional Shareholding | Basic / Often Empty | 12Q Quarterly & 11Y Annual Trends (Promoter, FII, DII, Govt, Public) |
| Conference Calls & Transcripts | ❌ None | 40+ Concalls with Direct Audio MP3s, BSE PDFs & Presentations |
| Annual Reports & Credit Ratings | ❌ None | 15+ Years Annual Report PDFs & CRISIL/ICRA Credit Rationales |
| Sector & Industry Hierarchy | Generic Global Taxonomy | 4-Level Indian Taxonomy + Index Memberships (Nifty 50, Sensex) |
| Institutional Stock Screens | ❌ None | Built-in Screens: Coffee Can, Magic Formula, Debt-Free, High Yield |
| Custom Ratios & Scoring | ❌ None | Piotroski 9-Point Score, Graham Number, EV/EBITDA, Screener search |
| Excel Financial Modeling | ❌ None | 1-Line Multi-Tab .xlsx Export matching Screener "Export to Excel" |
| AI / LLM Context Engine | ❌ None | Native Token-Dense Markdown/JSON Dossiers & Prompt Factories |
| Anti-Blocking Architecture | ❌ None | Persistent SQLite Cache (24h TTL), User-Agent pool, Jitter pacing |
📦 Installation
# Using pip
pip install bfinance
# Using uv (recommended)
uv add bfinance
⚡ 30-Second Quickstart (Migrating from yfinance)
Replace import yfinance as yf with import bfinance as yf. The members used below behave the
same way; this is a subset, not a drop-in — read the breaks in
docs/YFINANCE_PARITY.md §8 before switching an existing codebase:
import bfinance as yf
# 1. Initialize any NSE or BSE ticker (supports RELIANCE, RELIANCE.NS, 500325.BO)
ticker = yf.Ticker("RELIANCE")
# 2. yfinance 1.7.0-shaped APIs used here work out of the box
print("Live CMP:", ticker.fast_info.last_price)
print("Market Cap:", ticker.fast_info.market_cap)
# Historical OHLCV (Exact DataFrame schema with Dividends & Splits)
hist = ticker.history(period="1mo", actions=True)
print(hist.tail())
# 3. Access 10-Year Audited Financial Statements
print(ticker.financials) # 10+ Years Ind AS Annual Income Statement
print(ticker.balance_sheet) # 10+ Years Annual Balance Sheet
print(ticker.cashflow) # 10+ Years Cash Flow Statement
print(ticker.quarterly_income_stmt) # 12+ Quarters Results
# Opt-in: where Screener.in has no statement at all, fall back to Trendlyne (own row
# labels; provider + basis on df.attrs — see docs/API_REFERENCE.md §2.3.1)
fb = yf.Ticker("RELIANCE", statement_fallback=True).financials
# 4. Multi-ticker downloading (yf.download equivalent)
data = yf.download(["TCS", "INFY", "HDFCBANK"], period="5d")
💎 Indian Market Superpowers
1. Conference Calls with Direct Audio MP3 Streaming
Access over 40+ historical quarterly earnings calls, download PDFs, and stream raw audio:
import bfinance as bf
stock = bf.Ticker("TCS")
for call in stock.concalls[:3]:
print(f"[{call.date}] {call.title}")
print(" • PDF Transcript:", call.transcript_url)
print(" • Audio MP3 Link:", call.audio_url)
# Download the latest concall audio MP3 straight to disk
stock.download_concall_audio(index=0, dest_path="./tcs_concall.mp3")
# Download the latest transcript PDF
stock.download_concall_transcript(index=0, dest_path="./tcs_transcript.pdf")
2. Dual Cadence Institutional Shareholding Trends
Track institutional accumulation across FIIs, Mutual Funds, and Promoters:
stock = bf.Ticker("RELIANCE")
# 12+ Quarters Distribution
print("Quarterly Shareholding (12Q):\n", stock.shareholding)
# 11+ Years Historical Long-Term Trend
print("Annual Shareholding (11Y):\n", stock.shareholding_yearly)
3. Complete 4-Level Sector Hierarchy & Index Memberships
stock = bf.Ticker("RELIANCE")
print("Sector:", stock.sector) # Energy
print("Industry Group:", stock.industry_group) # Oil, Gas & Consumable Fuels
print("Industry:", stock.industry) # Petroleum Products
print("Sub-Industry:", stock.sub_industry) # Refineries & Marketing
print("Indices:", stock.indices) # ['BSE Sensex', 'Nifty 50', 'BSE 500', ...]
4. Custom Ratios & Quantitative Scoring Engine
Search Screener's 500+ ratio directory and compute advanced investment metrics:
stock = bf.Ticker("RELIANCE")
# 1. Joseph Piotroski 9-Point F-Score
print("Piotroski Score:", stock.piotroski_score, "/ 9")
# 2. Benjamin Graham Maximum Fair Value
print("Graham Number: ₹", stock.graham_number)
# 3. Enterprise Value & Multiples
# enterprise_value is Optional[float]: it is None when a leg of mcap + debt - cash is not in
# hand, which is the normal case -- the upstream balance sheet does not itemise cash (it sits
# inside an undifferentiated "Other Assets" bucket), so the cash leg is unsourceable and is
# omitted rather than assumed to be zero. bfinance_enterprise_value_omitted says which leg is
# missing. ev_to_ebitda follows the same omission.
print("Enterprise Value: ₹", stock.enterprise_value, "Cr")
print("EV / EBITDA:", stock.ev_to_ebitda, "x")
print("Interest Coverage Ratio:", stock.interest_coverage, "x")
if stock.enterprise_value is None:
print(" (omitted:", stock.custom_ratios["bfinance_enterprise_value_omitted"] + ")")
# 4. Search Screener's 500+ ratio catalog
results = bf.ratios.search("graham")
for r in results:
print(r["name"], "->", r["description"])
5. Institutional Stock Screeners
Run pre-built institutional strategies or custom filters:
import bfinance as bf
# 1. Saurabh Mukherjea Coffee Can (10Y ROCE > 15% & ROE > 15%)
coffee_df = bf.screens.coffee_can.run(max_stocks=10)
print(coffee_df[['Symbol', 'Name', 'Price', 'ROCE_%', 'ROE_%']])
# 2. Joel Greenblatt Magic Formula (High ROCE + Attractive P/E)
magic_df = bf.screens.magic_formula.run(max_stocks=10)
# 3. Other built-in screens
bf.screens.debt_free_compounders.run()
bf.screens.high_dividend_yield.run()
bf.screens.undervalued_growth.run()
# 4. Custom Screener Predicate
growth_screen = bf.screens.custom(
name="High ROE Midcaps",
filter_fn=lambda t: (t.info.get("marketCapInCr") or 0) > 10000 and ((t.info.get("returnOnEquity") or 0) * 100) > 20
)
print(growth_screen.run(max_stocks=5))
6. 1-Line Multi-Tab Excel Financial Model Exporter
Export complete 10+ year statements and valuation ratios into an 8-sheet .xlsx workbook matching Screener's "Export to Excel":
stock = bf.Ticker("RELIANCE")
stock.to_excel("Reliance_10Y_Financial_Model.xlsx")
Generates sheets: Overview, Profit & Loss, Quarters, Balance Sheet, Cash Flow, Shareholding, Ratios History, and Peers.
7. Opt-in Trendlyne Sections (broker reports, shareholding, deals, F&O chains)
bfinance.trendlyne is a separate, isolated third-party package — nothing else in bfinance
imports it, and import bfinance never pulls it in. It reaches data no Indian exchange or official
source publishes free: broker research targets, share-holding patterns, bulk/block deals, insider
trades, board meetings, SWOT, vendor technical signals, and option chains. It is off by default
and must be asked for by name.
import bfinance as bf
# One flag on the constructor. Off by default; no existing property changes behaviour.
t = bf.Ticker("TCS", trendlyne_sections=True)
# Seven members it adds — each degrades to an honest empty shape, reason on t.data_warnings
t.trendlyne_news() # yfinance {id, content{...}} shape, paginated
t.trendlyne_reports() # broker research table + LTP + Target + Upside
t.trendlyne_shareholding() # holder categories down, quarters across
t.trendlyne_deals() # bulk & block deals, full served history
t.trendlyne_buy_sell_zone() # {"standalone": df, "consolidated": df} PE-band grids
t.trendlyne_technicals() # vendor signals: name / value / insight / color
t.trendlyne_swot() # the five SWOT fact tables
# And the one that changes an existing property from None to a real number:
t.analyst_price_targets
# {'current': None, 'low': ..., 'high': ..., 'mean': ..., 'median': ...,
# 'n_reports': 20, 'bfinance_analyst_source': 'trendlyne_research_reports'}
current is always None on that path — the vendor's LTP column is the price at each
report's publication, not today's — and the vendor's own aggregate "Consensus Share Price
Target" row is excluded from the statistics. See
docs/YFINANCE_MIGRATION_GUIDE.md §3.E.
Two more opt-in surfaces, both reached by an explicit import:
# Local technical indicators — pure pandas over history(), no network, no robots question
from bfinance.market.technical import TechnicalIndicators as TI
h = bf.Ticker("TCS").history(period="1y")
TI.rsi(h, 14) # Wilder RSI; a short window yields no value, never 0.0
TI.macd(h) # {"macd": ..., "signal": ..., "histogram": ...}
TI.bollinger(h) # {"mid": ..., "upper": ..., "lower": ..., "pct_b": ...}
TI.pivots(h) # classic / woodie / camarilla / fibonacci, off the last bar
TI.snapshot(h) # the whole set as one dict (close, sma_20/50/200, rsi_14, …)
# Option chains — a different host (smartoptions.trendlyne.com), gated by its own flag
from bfinance.trendlyne.smartoptions import SmartOptionsClient
chain = SmartOptionsClient(allow_smart_options=True).option_chain("TCS", "2026-10-27")
chain.chain # long frame, one row per strike x side
chain.summary # maxPain, atTheMoney, MWPL, PCR vol/OI
allow_smart_options defaults to False and the call raises before a socket opens. The
expiry must be ISO YYYY-MM-DD — 27-Oct-2026 is a server 500. bfinance.trendlyne also
honours trendlyne's robots.txt: one page route (/equity/technical-analysis-*) and the two
alert write routes stay unwired, and the member-autocomplete route is behind its own opt-in.
docs/API_REFERENCE.md §2.3.2 has the full surface; docs/UPSTREAM_SOURCES.md §4 has the
measurements behind every claim here.
🤖 Native AI / LLM Data Feed Engine
Feed 100% of corporate data directly to AI agents (Gemini, Claude, GPT, DeepSeek, LangChain, LlamaIndex, CrewAI):
stock = bf.Ticker("RELIANCE")
# 1. Generate token-dense Markdown financial dossier
markdown_dossier = stock.to_ai_context(format="markdown")
# 2. Or generate structured JSON dictionary
json_dossier = stock.to_ai_context(format="json")
# 3. Ready-to-run prompt templates
memo_prompt = stock.to_investment_memo_prompt() # Initiation Coverage Note
audit_prompt = stock.to_forensic_audit_prompt() # Forensic Accounting Check
concall_prompt = stock.to_concall_analyst_prompt() # Earnings Call Analysis
AI Agent Function Calling Tools
from bfinance.ai import BFinanceAITools
# Get native OpenAI / Gemini tool calling schemas
tools = BFinanceAITools.get_openai_tools()
# Execute tool call returned by LLM
result = BFinanceAITools.execute_tool(
name="get_stock_dossier",
arguments={"symbol": "TCS", "format": "markdown"}
)
🛡️ Anti-Blocking & Zero-Crash Architecture
bfinance is engineered for production environments where reliability and uptime are paramount:
- Persistent SQLite Caching (
~/.cache/bfinance/cache.db):- Fundamentals cached for 24 hours, search queries for 7 days, chart timeseries for 6 hours.
- 99% of requests resolve in < 1ms from disk cache without touching remote servers.
- Adaptive Request Pacing & Jitter:
- Automatic
150mspacing +10–50msGaussian micro-jitter to prevent WAF burst detection.
- Automatic
- Desktop Browser Pool Rotation:
- Automatically rotates realistic Chrome, Safari, Firefox, and Edge user-agents with complete browser headers.
- Exponential Backoff:
- Recovers gracefully from HTTP 429 rate limits without aggressive retry spam.
- Zero-Crash Graceful Degradation (
raise_errors=Falsedefault):- Missing data, invalid symbols, or delisted companies log structured warnings via standard Python
loggingand return safe empty DataFrames/dictionaries instead of throwing uncaught exceptions.
- Missing data, invalid symbols, or delisted companies log structured warnings via standard Python
📚 Detailed Documentation & Guides
- 📖 API Reference Manual: Exhaustive function-by-function guide.
- 🔄 yfinance Migration Guide: Step-by-step migration notes.
- 🤖 AI Agent Integration Guide: Using
bfinancewith LangChain, LlamaIndex, CrewAI, and OpenAI/Gemini. - 🧪 Contributing & Development: Testing and development setup.
🧪 Test Suite
bfinance maintains an exhaustive test suite with 54/54 tests passing:
# Run full test suite with uv
uv run pytest
📄 License & Legal Disclaimers
License
This project is licensed under the MIT License. See LICENSE for complete terms.
⚠️ Legal, Financial & Non-Affiliation Disclaimer
- Educational & Academic Purpose Only:
bfinanceis an open-source software library developed strictly for academic, educational, and research purposes. It is NOT financial, investment, accounting, tax, or legal advice. - No Investment Liability: The developers, maintainers, and contributors are not SEBI-registered Research Analysts (RA) or Investment Advisors (RIA). No output from this library constitutes a recommendation or solicitation to buy, sell, or hold any security or financial derivative. Users assume 100% full responsibility for their own financial decisions and trading operations. In no event shall the authors be liable for any direct, indirect, or consequential financial losses.
- Independent Project & Non-Affiliation:
bfinanceis an independent open-source project and is not affiliated, endorsed, authorized, or certified by Yahoo! Inc.,yfinance, Screener.in (Mittal Analytics), NSE India, BSE India, or any of their parent entities or subsidiaries. All product names, trademarks, ticker symbols, and brand logos belong to their respective owners. - Data Verification & Fair Usage: Data is fetched from publicly accessible endpoints. Users are responsible for complying with the Terms of Service and rate limits of any upstream platforms. For mission-critical commercial applications, users should subscribe to official authorized market data providers.
Metadata
Release files for bfinance 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| bfinance-0.2.0.tar.gz | 4.1 MB | Without provenance | Details for bfinance-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| bfinance-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for bfinance-0.2.0-py3-none-any.whl |
Total release size: 4.9 MB
Release files / bfinance-0.2.0.tar.gz
| Download URL | bfinance-0.2.0.tar.gz |
|---|---|
| Size | 4.1 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c690a8c9905433217a9a7bb2d70bfb3f57646c2648682121a943995561f79c75
|
|
BLAKE2b-256 checksum How to use checksums |
4f6788ed9e37b1a7c8dce70cb60678d416e3947b54e89aed9b9c5da3e2643787
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / bfinance-0.2.0-py3-none-any.whl
| Download URL | bfinance-0.2.0-py3-none-any.whl |
|---|---|
| Size | 760.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7ae6ec9845324599152130ae56ebf97684536affc644f90d7212c24c15f1adda
|
|
BLAKE2b-256 checksum How to use checksums |
49038cb58f47812c247afc3e0be08d4c3d3296629d9b67fa4e464b15bad037e1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for bfinance 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.