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.
Installation
Section titled “Installation”Install the SDK using pip:
pip install finbrain-pythonQuick Start
Section titled “Quick Start”from finbrain import FinBrainClient
# Initialize with your API keyfb = FinBrainClient(api_key="YOUR_API_KEY")
# Get AI predictionspredictions = fb.predictions.ticker("AAPL", prediction_type="daily")print(f"Expected Short: {predictions['prediction']['expectedShort']}")
# Get insider transactionsinsiders = fb.insider_transactions.ticker("S&P 500", "AAPL")print(insiders["insiderTransactions"])
# Get sentiment scoressentiment = fb.sentiments.ticker("S&P 500", "AAPL")print(sentiment["sentimentAnalysis"])Configuration
Section titled “Configuration”API Key from Environment Variable
Section titled “API Key from Environment Variable”import osfrom finbrain import FinBrainClient
# Load API key from environmentfb = FinBrainClient(api_key=os.environ.get("FINBRAIN_API_KEY"))Set environment variable:
Section titled “Set environment variable:”export FINBRAIN_API_KEY="your_api_key_here"Methods Reference
Section titled “Methods Reference”Discovery Methods
Section titled “Discovery Methods”fb.available.markets()
Section titled “fb.available.markets()”Get all available markets.
markets = fb.available.markets()print(markets["markets"])# ['S&P 500', 'NASDAQ', 'NYSE', 'Dow Jones', 'Russell 2000', 'Crypto']fb.available.tickers(prediction_type)
Section titled “fb.available.tickers(prediction_type)”Get all tickers with predictions available.
# Get tickers with daily predictionstickers = fb.available.tickers(prediction_type="daily")print(f"Found {len(tickers['tickers'])} tickers")
# Get tickers with monthly predictionsmonthly_tickers = fb.available.tickers(prediction_type="monthly")Prediction Methods
Section titled “Prediction Methods”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 predictionspredictions = 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 predictionsmonthly = fb.predictions.ticker("AAPL", prediction_type="monthly")
# Get historical predictionshistorical = 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 predictionspredictions = fb.predictions.market("S&P 500", prediction_type="daily")
# Iterate through predictionsfor item in predictions: ticker = item["ticker"] pred = item["prediction"] print(f"{ticker}: Short={pred['expectedShort']}, Mid={pred['expectedMid']}")Alternative Data Methods
Section titled “Alternative Data Methods”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 datesentiment_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 ratingsfor 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']}")DataFrame Support
Section titled “DataFrame Support”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.
Predictions DataFrame
Section titled “Predictions DataFrame”# Get price forecasts as a DataFramedf = 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.08Market Predictions DataFrame
Section titled “Market Predictions DataFrame”# Screen entire market with DataFrame outputdf = 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 signalsbullish = df[df["expectedLong"] > 2.0]print(f"Found {len(bullish)} bullish stocks")Sentiment DataFrame
Section titled “Sentiment DataFrame”# Get sentiment as time seriesdf = 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 averagedf["sentiment_ma"] = df["sentiment"].rolling(5).mean()Alternative Data DataFrames
Section titled “Alternative Data DataFrames”# Insider transactionsdf = fb.insider_transactions.ticker("S&P 500", "AAPL", as_dataframe=True)# Index: date, Columns: insiderTradings, relationship, transaction, shares, cost, USDValue, etc.
# House tradesdf = fb.house_trades.ticker("S&P 500", "NVDA", as_dataframe=True)# Index: date, Columns: representative, type, amount
# Analyst ratingsdf = fb.analyst_ratings.ticker("S&P 500", "AAPL", as_dataframe=True)# Index: date, Columns: institution, signal, targetPrice, type
# Options put/call ratiodf = fb.options.put_call("S&P 500", "AAPL", as_dataframe=True)# Index: date, Columns: ratio, callCount, putCount
# LinkedIn datadf = fb.linkedin_data.ticker("S&P 500", "META", as_dataframe=True)# Index: date, Columns: employeeCount, followersCount
# App ratingsdf = fb.app_ratings.ticker("S&P 500", "UBER", as_dataframe=True)# Index: date, Columns: playStoreScore, appStoreScore, playStoreRatingsCount, etc.DataFrame Methods Summary
Section titled “DataFrame Methods Summary”| Method | DataFrame Index | Key Columns |
|---|---|---|
predictions.ticker() | datetime | main, lower, upper |
predictions.market() | ticker | expectedShort, expectedMid, expectedLong, sentimentScore |
sentiments.ticker() | datetime | sentiment |
insider_transactions.ticker() | datetime | insiderTradings, transaction, shares, USDValue |
house_trades.ticker() | datetime | representative, type, amount |
analyst_ratings.ticker() | datetime | institution, signal, targetPrice |
options.put_call() | datetime | ratio, callCount, putCount |
linkedin_data.ticker() | datetime | employeeCount, followersCount |
app_ratings.ticker() | datetime | playStoreScore, appStoreScore |
Complete Example
Section titled “Complete Example”from finbrain import FinBrainClient
# Initializefb = 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 tickersfor ticker in ["AAPL", "MSFT", "NVDA"]: analyze_ticker("S&P 500", ticker)Error Handling
Section titled “Error Handling”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 appropriatelySource Code
Section titled “Source Code”The Python SDK is open source: