Python SDK Documentation
The official Python SDK provides a simple, Pythonic interface to the FinBrain v2 API. Fetch deep-learning price predictions, sentiment scores, insider trades, LinkedIn metrics, options data and more — with a single import.
Requirements: Python 3.9+ with requests, pandas, numpy & plotly. Asyncio optional.
- PyPI: finbrain-python
- GitHub: github.com/ahmetsbilgin/finbrain-python
Features
Section titled “Features”- One-line auth (
FinBrainClient(api_key="…")) with Bearer token authentication - Complete v2 endpoint coverage (predictions, sentiments, news, screener, options, insider, etc.)
- Transparent retries & custom error hierarchy (
FinBrainError) - Async parity with
finbrain.aio(httpx) as_dataframe=Trueon every endpoint for pandas DataFrames- MIT-licensed, fully unit-tested
Installation
Section titled “Installation”pip install finbrain-pythonQuick Start
Section titled “Quick Start”from finbrain import FinBrainClient
fb = FinBrainClient(api_key="YOUR_KEY") # create once, reuse below
# ---------- discovery ----------fb.available.markets() # list marketsfb.available.tickers("daily", as_dataframe=True)fb.available.regions() # markets grouped by region
# ---------- predictions ----------fb.predictions.ticker("AMZN", as_dataframe=True)fb.predictions.ticker("AMZN", prediction_type="monthly", as_dataframe=True)
# ---------- sentiments ----------fb.sentiments.ticker("AMZN", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True)
# ---------- news ----------fb.news.ticker("AMZN", as_dataframe=True)
# ---------- insider transactions ----------fb.insider_transactions.ticker("AMZN", as_dataframe=True)
# ---------- house trades ----------fb.house_trades.ticker("AMZN", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True)
# ---------- senate trades ----------fb.senate_trades.ticker("META", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True)
# ---------- analyst ratings ----------fb.analyst_ratings.ticker("AMZN", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True)
# ---------- options put/call ----------fb.options.put_call("AMZN", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True)
# ---------- LinkedIn metrics ----------fb.linkedin_data.ticker("AMZN", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True)
# ---------- app ratings ----------fb.app_ratings.ticker("AMZN", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True)
# ---------- corporate lobbying ----------fb.corporate_lobbying.ticker("AAPL", date_from="2025-01-01", date_to="2025-12-31", as_dataframe=True)
# ---------- reddit mentions ----------fb.reddit_mentions.ticker("TSLA", as_dataframe=True)
# ---------- screener (cross-ticker) ----------fb.screener.predictions_daily(market="S&P 500", as_dataframe=True)fb.screener.insider_trading(as_dataframe=True)fb.screener.sentiment(market="NASDAQ", as_dataframe=True)fb.screener.reddit_mentions(as_dataframe=True)
# ---------- recent ----------fb.recent.news(limit=20, as_dataframe=True)fb.recent.analyst_ratings(limit=10, as_dataframe=True)Async Usage
Section titled “Async Usage”For async/await support, install with the async extra:
pip install finbrain-python[async]Then use AsyncFinBrainClient with httpx:
import asynciofrom finbrain.aio import AsyncFinBrainClient
async def main(): async with AsyncFinBrainClient(api_key="YOUR_KEY") as fb: # All methods are async and return the same data structures markets = await fb.available.markets()
# Fetch predictions predictions = await fb.predictions.ticker("AMZN", as_dataframe=True)
# Fetch sentiment data sentiment = await fb.sentiments.ticker( "AMZN", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True )
# All other endpoints work the same way news = await fb.news.ticker("AMZN", as_dataframe=True) screener = await fb.screener.predictions_daily(market="S&P 500", as_dataframe=True)
asyncio.run(main())Note: The async client uses httpx.AsyncClient and must be used with async with context manager for proper resource cleanup.
Plotting
Section titled “Plotting”Plot helpers for visualizing FinBrain data. All plot methods support:
show– defaults to True, so the chart appears immediatelyas_json=True– skips display and returns the figure as a Plotly-JSON stringtemplate– Plotly template name (default:"plotly_dark")
# ---------- App Ratings Chart - Apple App Store or Google Play Store ----------fb.plot.app_ratings("AMZN", store="app", # "play" for Google Play Store date_from="2025-01-01", date_to="2025-06-30")
# ---------- LinkedIn Metrics Chart ----------fb.plot.linkedin("AMZN", date_from="2025-01-01", date_to="2025-06-30")
# ---------- Put-Call Ratio Chart ----------fb.plot.options("AMZN", kind="put_call", date_from="2025-01-01", date_to="2025-06-30")
# ---------- Predictions Chart ----------fb.plot.predictions("AMZN") # prediction_type="monthly" for monthly predictions
# ---------- Sentiments Chart ----------fb.plot.sentiments("AMZN", date_from="2025-01-01", date_to="2025-06-30")
# ---------- Insider Transactions, House & Senate Trades (requires user price data) ----------# These plots overlay transaction markers on a price chart.# Since FinBrain doesn't provide historical prices, you must provide your own:
import pandas as pd
# Example: Load your price data from any legal source# (broker API, licensed data provider, CSV file, etc.)price_df = pd.DataFrame({ "close": [150.25, 151.30, 149.80], # Your price data "date": pd.date_range("2025-01-01", periods=3)}).set_index("date")
# Plot insider transactions on your price chartfb.plot.insider_transactions("AAPL", price_data=price_df)
# Plot House member trades on your price chartfb.plot.house_trades("NVDA", price_data=price_df, date_from="2025-01-01", date_to="2025-06-30")
# Plot Senate member trades on your price chartfb.plot.senate_trades("META", price_data=price_df, date_from="2025-01-01", date_to="2025-06-30")
# Plot corporate lobbying filings on your price chartfb.plot.corporate_lobbying("AAPL", price_data=price_df, date_from="2025-01-01", date_to="2025-06-30")Price Data Requirements:
- DataFrame with DatetimeIndex
- Must contain a price column:
close,Close,price,Price,adj_close, orAdj Close - Obtain from legal sources: broker API, Bloomberg, Alpha Vantage, FMP, etc.
Authentication
Section titled “Authentication”To call the API you need an API key, obtained by purchasing a FinBrain API subscription.
(The Terminal-only subscription does not include an API key.)
- Subscribe at finbrain.tech → FinBrain API
- Copy the key from your dashboard
- Pass it once when you create the client:
from finbrain import FinBrainClientfb = FinBrainClient(api_key="YOUR_KEY")Or set the FINBRAIN_API_KEY environment variable and omit it:
fb = FinBrainClient() # reads from FINBRAIN_API_KEY env varThe SDK uses Bearer token authentication (Authorization: Bearer YOUR_KEY) automatically.
Client Options
Section titled “Client Options”fb = FinBrainClient( api_key="YOUR_KEY", base_url="https://api.finbrain.tech/v2/", # default timeout=10, # request timeout in seconds retries=3, # retry count for 500 errors)After any API call, response metadata is available via fb.last_meta:
predictions = fb.predictions.ticker("AAPL", as_dataframe=True)print(fb.last_meta) # {"timestamp": "2026-03-09T12:34:56Z"}Supported Endpoints
Section titled “Supported Endpoints”Per-Ticker Endpoints
Section titled “Per-Ticker Endpoints”| Category | Method | Key DataFrame Columns |
|---|---|---|
| Predictions | client.predictions.ticker(symbol) | mid, lower, upper |
| Sentiments | client.sentiments.ticker(symbol) | sentiment |
| News | client.news.ticker(symbol) | headline, source, sentiment |
| Insider transactions | client.insider_transactions.ticker(symbol) | insider, transactionType, shares, totalValue |
| House trades | client.house_trades.ticker(symbol) | politician, transactionType, amount |
| Senate trades | client.senate_trades.ticker(symbol) | politician, transactionType, amount |
| Analyst ratings | client.analyst_ratings.ticker(symbol) | action, institution, rating, targetPrice |
| Options | client.options.put_call(symbol) | ratio, callVolume, putVolume |
client.linkedin_data.ticker(symbol) | employeeCount, followerCount | |
| App ratings | client.app_ratings.ticker(symbol) | ios_score, android_score, android_installCount |
| Corporate lobbying | client.corporate_lobbying.ticker(symbol) | clientName, registrantName, income, expenses, issueCodes |
Discovery Endpoints
Section titled “Discovery Endpoints”| Category | Method |
|---|---|
| Markets | client.available.markets() |
| Tickers | client.available.tickers(prediction_type) |
| Regions | client.available.regions() |
Cross-Ticker Endpoints
Section titled “Cross-Ticker Endpoints”| Category | Method |
|---|---|
| Screener | client.screener.predictions_daily(market=...) |
client.screener.predictions_monthly(market=...) | |
client.screener.sentiment(market=...) | |
client.screener.insider_trading() | |
client.screener.congress_house() | |
client.screener.congress_senate() | |
client.screener.analyst_ratings() | |
client.screener.news() | |
client.screener.put_call_ratio() | |
client.screener.linkedin() | |
client.screener.app_ratings() | |
| Recent | client.recent.news() |
client.recent.analyst_ratings() |
See API Reference for endpoint paths and parameters.
Error Handling
Section titled “Error Handling”from finbrain.exceptions import BadRequest, RateLimitError
try: fb.predictions.ticker("MSFT", prediction_type="weekly")except BadRequest as exc: print("Invalid parameters:", exc) print("Error code:", exc.error_code) # e.g., "VALIDATION_ERROR" print("Details:", exc.error_details) # structured error detailsexcept RateLimitError: print("Rate limit exceeded — wait and retry")| HTTP status | Exception class | Meaning |
|---|---|---|
| 400 | BadRequest | The request is invalid or malformed |
| 401 | AuthenticationError | API key missing or incorrect |
| 403 | PermissionDenied | Authenticated, but not authorised |
| 404 | NotFound | Resource or endpoint not found |
| 405 | MethodNotAllowed | HTTP method not supported on endpoint |
| 429 | RateLimitError | Too many requests — rate limit hit |
| 500 | ServerError | FinBrain internal error |
All exceptions inherit from FinBrainError and expose .status_code, .error_code, .error_details, and .payload attributes.
Migration from v0.1.x
Section titled “Migration from v0.1.x”If upgrading from the v1 SDK:
| v0.1.x (v1 API) | v0.2.0 (v2 API) |
|---|---|
fb.sentiments.ticker("S&P 500", "AAPL") | fb.sentiments.ticker("AAPL") |
fb.insider_transactions.ticker("S&P 500", "AAPL") | fb.insider_transactions.ticker("AAPL") |
fb.predictions.market("S&P 500") | fb.screener.predictions_daily(market="S&P 500") |
fb.sentiments.ticker(..., days=30) | fb.sentiments.ticker(..., date_from="...", date_to="...") |
DataFrame column main | DataFrame column mid |
DataFrame column followersCount | DataFrame column followerCount |
DataFrame columns callCount/putCount | DataFrame columns callVolume/putVolume |
Key change: The market parameter has been removed from all per-ticker methods. Just pass the symbol directly.
Development
Section titled “Development”git clone https://github.com/ahmetsbilgin/finbrain-pythoncd finbrain-pythonpython -m venv .venv && source .venv/bin/activatepip install -e .[dev]
ruff check . # lint / formatpytest -q # unit tests (mocked)Security
Section titled “Security”Report vulnerabilities to info@finbrain.tech. We respond within 48 hours.