Skip to content

Python SDK Documentation

The official Python SDK provides a simple, Pythonic interface to the FinBrain API. Access AI predictions, insider trading data, sentiment analysis, and all other datasets with just a few lines of code.

Install the SDK using pip:

Terminal window
pip install finbrain-python
from finbrain import FinBrainClient
# Initialize with your API key
fb = FinBrainClient(api_key="YOUR_API_KEY")
# Get AI predictions
predictions = fb.predictions.ticker("AAPL", prediction_type="daily")
print(f"Expected Short: {predictions['prediction']['expectedShort']}")
# Get insider transactions
insiders = fb.insider_transactions.ticker("S&P 500", "AAPL")
print(insiders["insiderTransactions"])
# Get sentiment scores
sentiment = fb.sentiments.ticker("S&P 500", "AAPL")
print(sentiment["sentimentAnalysis"])
import os
from finbrain import FinBrainClient
# Load API key from environment
fb = FinBrainClient(api_key=os.environ.get("FINBRAIN_API_KEY"))
Terminal window
export FINBRAIN_API_KEY="your_api_key_here"

Get all available markets.

markets = fb.available.markets()
print(markets["markets"])
# ['S&P 500', 'NASDAQ', 'NYSE', 'Dow Jones', 'Russell 2000', 'Crypto']

Get all tickers with predictions available.

# Get tickers with daily predictions
tickers = fb.available.tickers(prediction_type="daily")
print(f"Found {len(tickers['tickers'])} tickers")
# Get tickers with monthly predictions
monthly_tickers = fb.available.tickers(prediction_type="monthly")

fb.predictions.ticker(ticker, prediction_type, date_from=None, date_to=None)

Section titled “fb.predictions.ticker(ticker, prediction_type, date_from=None, date_to=None)”

Get AI price predictions for a specific ticker.

# Get daily predictions
predictions = fb.predictions.ticker("AAPL", prediction_type="daily")
pred = predictions["prediction"]
print(f"Expected Short: {pred['expectedShort']}%")
print(f"Expected Mid: {pred['expectedMid']}%")
print(f"Expected Long: {pred['expectedLong']}%")
# Get monthly predictions
monthly = fb.predictions.ticker("AAPL", prediction_type="monthly")
# Get historical predictions
historical = fb.predictions.ticker(
"AAPL",
prediction_type="daily",
date_from="2024-01-01",
date_to="2024-01-31"
)

fb.predictions.market(market, prediction_type)

Section titled “fb.predictions.market(market, prediction_type)”

Get predictions for all tickers in a market.

# Get all S&P 500 predictions
predictions = fb.predictions.market("S&P 500", prediction_type="daily")
# Iterate through predictions
for item in predictions:
ticker = item["ticker"]
pred = item["prediction"]
print(f"{ticker}: Short={pred['expectedShort']}, Mid={pred['expectedMid']}")

fb.sentiments.ticker(market, ticker, date_from=None, date_to=None)

Section titled “fb.sentiments.ticker(market, ticker, date_from=None, date_to=None)”

Get news sentiment scores.

sentiment = fb.sentiments.ticker("S&P 500", "AAPL")
# Sentiment data is keyed by date
sentiment_data = sentiment["sentimentAnalysis"]
for date, score in list(sentiment_data.items())[:5]:
print(f"{date}: {score}")

fb.insider_transactions.ticker(market, ticker, date_from=None, date_to=None)

Section titled “fb.insider_transactions.ticker(market, ticker, date_from=None, date_to=None)”

Get SEC Form 4 insider trading data.

transactions = fb.insider_transactions.ticker("S&P 500", "AAPL")
for t in transactions["insiderTransactions"]:
print(f"{t['insiderTradings']} ({t['relationship']}): {t['transaction']} {t['shares']} shares at ${t['cost']}")
print(f" Total Value: ${t['USDValue']}, Filed: {t['SECForm4Date']}")

fb.house_trades.ticker(market, ticker, date_from=None, date_to=None)

Section titled “fb.house_trades.ticker(market, ticker, date_from=None, date_to=None)”

Get US House Representatives trading activity.

trades = fb.house_trades.ticker("S&P 500", "NVDA")
for t in trades["houseTrades"]:
print(f"{t['representative']}: {t['type']} {t['amount']} on {t['date']}")

fb.analyst_ratings.ticker(market, ticker, date_from=None, date_to=None)

Section titled “fb.analyst_ratings.ticker(market, ticker, date_from=None, date_to=None)”

Get Wall Street analyst ratings and price targets.

ratings = fb.analyst_ratings.ticker("S&P 500", "AAPL")
# Individual ratings
for r in ratings["analystRatings"]:
print(f"{r['date']}: {r['institution']} - {r['signal']} (Target: ${r['targetPrice']})")
print(f" Type: {r['type']}")

fb.options.put_call(market, ticker, date_from=None, date_to=None)

Section titled “fb.options.put_call(market, ticker, date_from=None, date_to=None)”

Get options put/call ratio data.

putcall = fb.options.put_call("S&P 500", "AAPL")
for pc in putcall["putCallData"]:
print(f"{pc['date']}: Ratio={pc['ratio']}, Calls={pc['callCount']}, Puts={pc['putCount']}")

fb.linkedin_data.ticker(market, ticker, date_from=None, date_to=None)

Section titled “fb.linkedin_data.ticker(market, ticker, date_from=None, date_to=None)”

Get LinkedIn employee and follower metrics.

linkedin = fb.linkedin_data.ticker("S&P 500", "META")
for data in linkedin["linkedinData"]:
print(f"{data['date']}: Employees={data['employeeCount']:,}, Followers={data['followersCount']:,}")

fb.app_ratings.ticker(market, ticker, date_from=None, date_to=None)

Section titled “fb.app_ratings.ticker(market, ticker, date_from=None, date_to=None)”

Get mobile app store ratings.

ratings = fb.app_ratings.ticker("S&P 500", "UBER")
for r in ratings["appRatings"]:
print(f"{r['date']}: iOS={r['appStoreScore']}, Android={r['playStoreScore']}")
print(f" iOS Reviews: {r['appStoreRatingsCount']}, Android Reviews: {r['playStoreRatingsCount']}")

All SDK methods support an as_dataframe parameter that returns pandas DataFrames instead of raw JSON. This is ideal for data analysis and backtesting workflows.

# Get price forecasts as a DataFrame
df = fb.predictions.ticker("AAPL", prediction_type="daily", as_dataframe=True)
print(df)
# main lower upper
# date
# 2024-11-04 201.33 197.21 205.45
# 2024-11-05 202.77 196.92 208.61
# 2024-11-06 203.99 196.90 211.08
# Screen entire market with DataFrame output
df = fb.predictions.market("S&P 500", prediction_type="daily", as_dataframe=True)
print(df)
# expectedShort expectedMid expectedLong sentimentScore
# ticker
# AAPL 0.22 0.58 0.25 0.186
# MSFT 1.15 1.82 2.10 0.342
# NVDA 2.31 3.45 4.12 0.521
# Filter for bullish signals
bullish = df[df["expectedLong"] > 2.0]
print(f"Found {len(bullish)} bullish stocks")
# Get sentiment as time series
df = fb.sentiments.ticker("S&P 500", "AAPL", as_dataframe=True)
print(df)
# sentiment
# date
# 2024-11-04 0.186
# 2024-11-01 0.339
# 2024-10-31 0.565
# Calculate rolling average
df["sentiment_ma"] = df["sentiment"].rolling(5).mean()
# Insider transactions
df = fb.insider_transactions.ticker("S&P 500", "AAPL", as_dataframe=True)
# Index: date, Columns: insiderTradings, relationship, transaction, shares, cost, USDValue, etc.
# House trades
df = fb.house_trades.ticker("S&P 500", "NVDA", as_dataframe=True)
# Index: date, Columns: representative, type, amount
# Analyst ratings
df = fb.analyst_ratings.ticker("S&P 500", "AAPL", as_dataframe=True)
# Index: date, Columns: institution, signal, targetPrice, type
# Options put/call ratio
df = fb.options.put_call("S&P 500", "AAPL", as_dataframe=True)
# Index: date, Columns: ratio, callCount, putCount
# LinkedIn data
df = fb.linkedin_data.ticker("S&P 500", "META", as_dataframe=True)
# Index: date, Columns: employeeCount, followersCount
# App ratings
df = fb.app_ratings.ticker("S&P 500", "UBER", as_dataframe=True)
# Index: date, Columns: playStoreScore, appStoreScore, playStoreRatingsCount, etc.
MethodDataFrame IndexKey Columns
predictions.ticker()datetimemain, lower, upper
predictions.market()tickerexpectedShort, expectedMid, expectedLong, sentimentScore
sentiments.ticker()datetimesentiment
insider_transactions.ticker()datetimeinsiderTradings, transaction, shares, USDValue
house_trades.ticker()datetimerepresentative, type, amount
analyst_ratings.ticker()datetimeinstitution, signal, targetPrice
options.put_call()datetimeratio, callCount, putCount
linkedin_data.ticker()datetimeemployeeCount, followersCount
app_ratings.ticker()datetimeplayStoreScore, appStoreScore
from finbrain import FinBrainClient
# Initialize
fb = FinBrainClient(api_key="YOUR_API_KEY")
def analyze_ticker(market, ticker):
"""Comprehensive analysis of a ticker"""
print(f"\n{'='*50}")
print(f"Analysis for {ticker}")
print('='*50)
# AI Predictions
predictions = fb.predictions.ticker(ticker, prediction_type="daily")
if predictions.get("prediction"):
pred = predictions["prediction"]
print(f"\nAI Prediction:")
print(f" Expected Short-term: {pred['expectedShort']}%")
print(f" Expected Mid-term: {pred['expectedMid']}%")
print(f" Expected Long-term: {pred['expectedLong']}%")
# Sentiment
sentiment = fb.sentiments.ticker(market, ticker)
if sentiment.get("sentimentAnalysis"):
sentiment_data = sentiment["sentimentAnalysis"]
dates = list(sentiment_data.keys())[:5]
print(f"\nSentiment (last 5 days):")
for date in dates:
print(f" {date}: {sentiment_data[date]}")
# Insider Activity
insiders = fb.insider_transactions.ticker(market, ticker)
if insiders.get("insiderTransactions"):
transactions = insiders["insiderTransactions"]
purchases = [t for t in transactions if "Buy" in t.get("transaction", "")]
sales = [t for t in transactions if "Sale" in t.get("transaction", "")]
print(f"\nInsider Activity:")
print(f" Recent Purchases: {len(purchases)}")
print(f" Recent Sales: {len(sales)}")
# Analyst Ratings
ratings = fb.analyst_ratings.ticker(market, ticker)
if ratings.get("analystRatings"):
analyst_data = ratings["analystRatings"]
print(f"\nAnalyst Ratings ({len(analyst_data)} recent):")
for r in analyst_data[:3]:
print(f" {r['date']}: {r['institution']} - {r['signal']} (${r['targetPrice']})")
# Analyze multiple tickers
for ticker in ["AAPL", "MSFT", "NVDA"]:
analyze_ticker("S&P 500", ticker)
from finbrain import FinBrainClient
fb = FinBrainClient(api_key="YOUR_API_KEY")
try:
predictions = fb.predictions.ticker("INVALID_TICKER", prediction_type="daily")
except Exception as e:
print(f"Error: {e}")
# Handle the error appropriately

The Python SDK is open source: