This is the full developer documentation for FinBrain API # Alternative Data for Systematic Edge > Research-grade alternative data with full history. Build with the API, plug it into your LLMs, or explore it in the Terminal — all from one platform. ## Data That Moves Before the Market Does Research-grade data with full history, normalized and ticker-mapped across every dataset. Deep historical granularity for backtesting and model training, production-clean for live systems. [Congressional Trades](/datasets/congressional-trading/) [US House and Senate member trading activity. Disclosure-based signals from STOCK Act filings.](/datasets/congressional-trading/) [Corporate Lobbying](/datasets/corporate-lobbying/) [Federal lobbying disclosures. Track corporate influence and regulatory exposure.](/datasets/corporate-lobbying/) [Government Contracts](/datasets/government-contracts/) [Federal contract awards mapped to tickers. Revenue signals from government spending.](/datasets/government-contracts/) [Patent Filings](/datasets/patent-filings/) [Track granted patents by ticker. A structured signal of innovation and R\&D output.](/datasets/patent-filings/) [Insider Transactions](/datasets/insider-transactions/) [Daily SEC Form 4 filings. Track executive purchases, sales, and option exercises.](/datasets/insider-transactions/) [News Sentiment](/datasets/sentiment/) [AI-powered sentiment scores from financial news. Gauge market mood and momentum.](/datasets/sentiment/) [LinkedIn Metrics](/datasets/linkedin-data/) [Track employee counts and follower growth. Early indicators of company trajectory.](/datasets/linkedin-data/) [App Store Ratings](/datasets/app-ratings/) [Mobile app performance data from iOS and Android stores. User sentiment signals.](/datasets/app-ratings/) [Reddit Mentions](/datasets/reddit-mentions/) [Track ticker mentions across Reddit communities like WallStreetBets and r/stocks.](/datasets/reddit-mentions/) [Price Forecasts](/datasets/ai-forecasts/) [Daily and monthly price forecasts with confidence intervals from time-series models.](/datasets/ai-forecasts/) [Analyst Ratings](/datasets/analyst-ratings/) [Track analyst upgrades, downgrades, and price target changes from major institutions.](/datasets/analyst-ratings/) [Put/Call Ratios](/datasets/put-call/) [Options market sentiment data. Monitor put/call ratios and options flow signals.](/datasets/put-call/) 12,000+ US Stocks & ETFs 20 Forecast Markets 12 Datasets 10 Years Avg. History 8 Years Delivering Data 99.9% API Uptime SLA ## Built for Institutional Research The qualities that make alternative data actually usable: deep history, broad coverage, granular records, and clean, ticker-mapped delivery. Deep History An average of 10 years of history across the core datasets — enough to train models and test strategies through different market regimes, not just the latest one. Full US Universe Alternative data across 12,000+ US stocks and ETFs — the full listed universe, not just the S\&P 500 — with price forecasts extending to 20 global markets. Granular Detail Not just daily aggregates: individual insider filings, congressional trades, lobbying disclosures, and contract awards — drill down to the single transaction. Normalized and Comparable Consistent, clean tabular formats across every dataset, with normalized scores — so values compare across tickers and over time. Mapped to Tradable Tickers News, lobbying filings, contracts, and app data are matched to the right ticker before you ever see them — the messy entity-matching is already done. Clean and Research-Ready Filing datasets are collected directly from the official disclosure systems, and every series is screened daily for errors, duplicates, and gaps — minutes from API key to analysis. **Evaluate before you commit.** Institutional clients get a 30-day free evaluation with live daily data and a trailing 24 months of history. We’ll scope the trial to your use case. [See How It Works](/enterprise/) ## Unlike Sources, Consistent Delivery The government and regulatory datasets arrive as scraped PDFs, Form 4 XML, a quarterly registry and a weekly bulk archive — each on its own clock and its own time anchor. Every dataset has its own pipeline running the same stages, and they all arrive through the same envelope, keyed to the same tickers. Sources Congressional Trading House Clerk · Senate eFD PDF and HTML filings, scraped — no bulk API exists Daily, \~1-day lagFiling date Insider Transactions SEC EDGAR Form 4 XML Daily, \~1-day lagForm 4 filing date Corporate Lobbying Senate LDA registry Official REST API Quarterly, \~30 days after quarter-endPosting timestamp Government Contracts USAspending.gov Public API, records upsert by award ID Weekly collectionCurrent-state panel Patent Filings USPTO Open Data Weekly grant XML plus a deep-history archive Weekly, grants issue TuesdaysGrant date Pipelines Each dataset runs its own pipeline, built for the source it collects from. Every one of them runs the same five stages. 1. 01 Collect & archive First-party from each source. The original filing is kept as the provenance record. 2. 02 Extract Free text, XML and scanned filings are parsed into that dataset's structured fields. 3. 03 Map to a security Registrants, awardees and assignees are resolved to a US-listed ticker. SEC and government datasets also carry the issuer CIK. 4. 04 Normalize Amounts to their statutory brackets with the as-filed string preserved, dates to ISO, and anything unreadable delivered flagged rather than dropped. 5. 05 Dedupe & verify Amendments and restatements collapse to one row per real event, checked against the collection archive. Delivery * REST APIJSON, date and limit filtering * Python SDKpandas DataFrames * MCP serverfor LLM research workflows * FinBrain Terminalscreeners and ticker pages * CSV exportstraight from the Terminal The same envelope, auth and ticker keys throughout. Field names are per dataset. Straight to Your Pipeline\ via REST API & SDKs ------------------- One integration for your engineering team. Build trading systems, research platforms, and client-facing applications in days. ### Deploy in Hours, Not Months A single REST API with full historical data and a consistent response envelope across all datasets. One integration covers everything — no vendor patchwork, no missing history. * **One envelope, all datasets** - Same response shape, auth and query parameters, so only the fields change per dataset * **Python SDK** - `pip install finbrain-python` for rapid prototyping and production use * **High-throughput access** - Built for backtesting, live trading, and platform integrations * **Deep data history** - Years of granular historical data for backtesting, model training, and research — full depth with Enterprise [Contact Us](/enterprise/)[Python SDK Docs](/integrations/python/) * Python ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get price forecasts predictions = fb.predictions.ticker("AAPL", as_dataframe=True) # Get insider trading data insider = fb.insider_transactions.ticker("AAPL", as_dataframe=True) # Get news sentiment sentiment = fb.sentiments.ticker("NVDA", as_dataframe=True) ``` * cURL ```bash # Get price forecasts curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" # Get insider transactions curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/insider-trading/AAPL" # Get sentiment data curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/sentiment/NVDA" ``` * JavaScript ```javascript const headers = { "Authorization": "Bearer YOUR_API_KEY" }; const BASE = "https://api.finbrain.tech/v2"; const predictions = await fetch( `${BASE}/predictions/daily/AAPL`, { headers } ).then(res => res.json()); const insider = await fetch( `${BASE}/insider-trading/AAPL`, { headers } ).then(res => res.json()); ``` * C++ ```cpp #include #include json get_predictions(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response, url = "https://api.finbrain.tech/v2/predictions/daily/" + symbol; std::string auth = "Authorization: Bearer " + api_key; struct curl_slist* hdrs = curl_slist_append(nullptr, auth.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hdrs); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(hdrs); curl_easy_cleanup(curl); return json::parse(response); } ``` * Rust ```rust use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, HeaderValue}; fn get_predictions(symbol: &str, api_key: &str) -> Result { let url = format!( "https://api.finbrain.tech/v2/predictions/daily/{}", symbol ); Client::new().get(&url) .header(AUTHORIZATION, HeaderValue::from_str( &format!("Bearer {}", api_key)).unwrap()) .send()?.json() } ``` From Data to Insights\ FinBrain Terminal ----------------- Give analysts and portfolio managers the same datasets through a visual interface — no engineering required. ![Real-Time Dashboard](/_astro/terminal-dashboard.fWJwmCTb.png) ![Geopolitical Intelligence](/_astro/terminal-intelligence.CwYov_Bi.png) ![Ticker Deep Dive](/_astro/terminal-ticker.x_84Nb4g.png) ![Commodities & Energy](/_astro/terminal-commodities.BeJPQLTd.png) ![15 Alternative Data Screeners](/_astro/terminal-screeners.CZ35KNjW.png) ![Transaction-Level Analysis](/_astro/terminal-insider-trading-screener.DRMGNRHI.png) ![Crypto Markets](/_astro/terminal-crypto.DhArRFZ7.png) #### Real-Time Dashboard Market command center with geopolitical monitor, AI signals, earnings calendar, treasury yields, and activity wire — everything you need in one view. #### Geopolitical Intelligence Interactive globe with global conflict and event data. Defense and OSINT analysis feeds. Futures positioning across all asset classes. #### Ticker Deep Dive Every dataset for any ticker — price forecasts with confidence intervals, sentiment charts, insider transactions, analyst ratings, lobbying filings, and Reddit activity. #### Commodities & Energy Crude oil inventories, natural gas storage, US production data, and futures positioning across energy, metals, and agriculture. #### 15 Alternative Data Screeners Filter 12,000+ US tickers by price forecasts, insider buying, congressional trades, lobbying, government contracts, Reddit mentions, and more. #### Transaction-Level Analysis Drill down to individual filings — analyze every insider purchase, congressional trade, lobbying disclosure, and government contract by transaction value, date, and entity. #### Crypto Markets Top coins by market cap, sentiment index, Bitcoin network stats, trending coins, and institutional futures positioning. [Try Terminal](https://terminal.finbrain.tech)[Terminal Docs](/terminal/overview/) Plug Alternative Data\ Into Your LLMs -------------- Give your team's AI assistants direct access to FinBrain data. Accelerate research workflows across the organization. ### AI-Native Data Access Use the Model Context Protocol (MCP) to connect FinBrain data to Claude, ChatGPT, and custom LLM applications. Multiply analyst productivity. * **Natural language queries** - Analysts query predictions, insider trades, and sentiment in plain English * **Claude Desktop integration** - Just `pip install finbrain-mcp` and add your config * **Custom LLM apps** - Build internal research copilots and client-facing AI tools * **Current to the last collection run** - Each dataset on its own documented cadence, daily for filings and market data [Contact Us](/enterprise/)[MCP Docs](/integrations/mcp/) Analyst asks Any congressional buying in AAPL before April 2024? the model picks a tool Tool call house\_trades\_by\_ticker(symbol="AAPL") the server returns rows 8 rows returned date · disclosureDate · politician · owner · transactionType · amount · amountFlag answered from those rows Answer 4 purchases to 4 sales across 6 members. Half in spouse or dependent-child accounts. Disclosure lag 0 to 42 days, median 26. Example exchange. Every figure is computed from the returned rows, not written by the model. ## Who FinBrain Is For Teams across the investment landscape build on the same rows — each through the access that fits how they work. Pick a team to see what they touch. Quant fundsPlatformsCorporate strategy ### Quant funds & systematic traders Add alternative signals to your research pipeline in days, not months. Full history for backtesting, clean daily delivery for production strategies. Python SDK client.house\_trades.ticker("AAPL") A DataFrame, ready to join to your factor set. | | date | disclosureDate | politician | owner | transactionType | amount | lag | | - | ---------- | -------------- | ----------------- | ----- | --------------- | ----------------- | --- | | 0 | 2024-01-10 | 2024-02-05 | Rohit Khanna | SP | Purchase | $1,001 - $15,000 | 26d | | 1 | 2024-01-10 | 2024-02-05 | Rohit Khanna | DC | Purchase | $1,001 - $15,000 | 26d | | 2 | 2024-01-18 | 2024-02-15 | Josh Gottheimer | JT | Sale (Partial) | $1,001 - $15,000 | 28d | | 3 | 2024-01-19 | 2024-01-24 | Blake Moore | SELF | Sale | $15,001 - $50,000 | 5d | | 4 | 2024-02-29 | 2024-02-29 | Pete Sessions | SP | Purchase | $360review | 0d | | 5 | 2024-03-13 | 2024-04-24 | Jonathan Jackson | JT | Sale | $15,001 - $50,000 | 42d | | 6 | 2024-04-23 | 2024-05-06 | Rohit Khanna | SP | Purchase | $1,001 - $15,000 | 13d | | 7 | 2024-05-09 | 2024-06-13 | Michael T. McCaul | SP | Sale | $15,001 - $50,000 | 35d | 8 of 275 AAPL rows. SP spouse, DC dependent child, JT joint — rows 0 and 1 are the same trade in two accounts, not a duplicate. ### Trading platforms & aggregators Offer your users 12 new datasets through a single integration. Redistribution and client-facing display rights come with the enterprise agreement. REST API GET /v2/congress/house/AAPL One envelope and one auth for every dataset. ``` { "trades": [ { "date": "2024-01-10", "politician": "Rohit Khanna", "owner": "SP", "transactionType": "Purchase", "amount": "$1,001 - $15,000", "amountFlag": null, "disclosureDate": "2024-02-05" }, { "date": "2024-02-29", "politician": "Pete Sessions", "owner": "SP", "transactionType": "Purchase", "amount": "$360", "amountFlag": "review", "disclosureDate": "2024-02-29" }, // … 273 more AAPL rows ] } ``` `amountFlag` ships as `"review"` where a filed amount could not be read as a statutory bracket. Flagged, never silently dropped. ### Corporate intelligence & strategy Track competitor hiring, lobbying, government contracts, and market sentiment — through the Terminal or your team's AI assistants, no engineering needed. MCP ask your assistant No engineering. The data reaches the analyst directly. “What did Congress do in AAPL through H1 2024?” Across **275 disclosed AAPL trades**, the eight in this window split **4 purchases** to **4 sales** across **6 members**. Half sat in **spouse or dependent-child accounts**. Disclosure lag ran from **same day** to **42 days**, median **26**. Example exchange. Every figure is computed from the rows in the other two tabs. ## Licensing & Plans Enterprise data licensing for funds, platforms, and research teams — plus self-serve plans for professionals. MonthlyAnnualSave 17% ### Professional Visual alternative data platform for traders and researchers. $199/month * Full access to the FinBrain Terminal for one user * 16 data screeners across 12 alternative datasets * 12,000+ US stocks & ETFs covered * Per-ticker pages with charts & tables * Real-time Dashboard & macro indicators * Geopolitical monitoring & OSINT feeds * Yield curves, COT positioning & more * Portfolio tracking & analytics * CSV export from every screener * Email support [Get Started](https://terminal.finbrain.tech/) For Teams ### Enterprise For funds, platforms, and teams with custom requirements. Custom * 12 ticker-mapped alternative datasets for US equities * Full REST API, Python SDK and MCP access, with rate limits sized to your pipelines * Complete history for backtesting, 10 to 20 years depending on the dataset * Collected first-party from official US government sources, with no aggregator in between * Filing dates delivered alongside transaction dates, so your backtests stay look-ahead-free * A free 30-day evaluation on live data before you commit * Rights to redistribute the data and display it to your own clients * Rights to train internal models and build AI products on the data * A dedicated account manager and a contractual SLA * Due-diligence and compliance documentation for your vendor review * FinBrain Terminal seats for your analysts, as an add-on [Contact Us](/enterprise/) ### Professional Visual alternative data platform for traders and researchers. $1,990/year * Full access to the FinBrain Terminal for one user * 16 data screeners across 12 alternative datasets * 12,000+ US stocks & ETFs covered * Per-ticker pages with charts & tables * Real-time Dashboard & macro indicators * Geopolitical monitoring & OSINT feeds * Yield curves, COT positioning & more * Portfolio tracking & analytics * CSV export from every screener * Email support [Get Started](https://terminal.finbrain.tech/) For Teams ### Enterprise For funds, platforms, and teams with custom requirements. Custom * 12 ticker-mapped alternative datasets for US equities * Full REST API, Python SDK and MCP access, with rate limits sized to your pipelines * Complete history for backtesting, 10 to 20 years depending on the dataset * Collected first-party from official US government sources, with no aggregator in between * Filing dates delivered alongside transaction dates, so your backtests stay look-ahead-free * A free 30-day evaluation on live data before you commit * Rights to redistribute the data and display it to your own clients * Rights to train internal models and build AI products on the data * A dedicated account manager and a contractual SLA * Due-diligence and compliance documentation for your vendor review * FinBrain Terminal seats for your analysts, as an add-on [Contact Us](/enterprise/) ## Frequently Asked Questions Common questions about integration, coverage, and enterprise plans. ### Getting Started Questions about API access and setup. ### Data & Coverage What data is available and how often it updates. ### Pricing & Support Subscription plans and support options. #### How do I get started? Sign up at terminal.finbrain.tech for instant access. Most users are in production within a day. Enterprise clients can contact sales for guided onboarding. #### What programming languages are supported? We provide an official Python SDK with pip install finbrain-python. For other languages, use our REST API directly with any HTTP client. #### What are the rate limits? API access is part of an Enterprise agreement, with rate limits sized to your team's throughput requirements. Evaluation trials run at 2,000 requests per hour. #### Can we redistribute or display the data to clients? Redistribution and client-facing display rights are available with our Enterprise plan. Contact sales to discuss licensing for your use case. #### Can we evaluate the data before subscribing? Yes. Institutional clients get a 30-day free evaluation with live daily data and a trailing 24 months of history across the full universe. Book a call and we'll scope the trial to your use case and onboard your team. #### What markets are covered? Our alternative datasets focus on US-listed assets — 12,000+ stocks and ETFs across NYSE and NASDAQ. Price forecasts additionally cover 20 global markets, including international equities, forex, crypto, and commodities, and news sentiment extends to selected international markets. #### How often is the data updated? Price forecasts and sentiment scores update daily before US market open. Insider transactions and congressional trades are collected daily as new filings are published, so a filed transaction is typically available within a business day. Individual dataset pages document exact cadences. #### How far back does historical data go? Historical depth varies by dataset. Our longest-running datasets carry 10+ years of history, corporate lobbying goes back 15+ years, and newer series are being backfilled toward similar depth. Full historical depth is delivered under an Enterprise agreement. The Professional plan is the FinBrain Terminal browser platform, which shows recent activity per ticker rather than full history. Price forecasts are delivered point-in-time and represent forward-looking predictions only — historical forecasts are not exposed via the API. #### How should we evaluate the price forecasts? Our forecasts are generated using ARIMA time-series models that capture the statistical properties of historical price movements and produce out-of-sample predictions with calibrated confidence intervals. Forecasts are delivered point-in-time — to evaluate them, capture the daily output and compare against realized prices over time. See the Price Forecasts dataset page for methodology details. #### Is the data suitable for backtesting? Yes — the disclosure datasets are built for it. Filings carry both the event date and the public disclosure date, so you can anchor a backtest on the moment information actually became public and keep it free of look-ahead bias. Core datasets carry 10+ years of history, up to 15 for corporate lobbying. Each dataset page documents the correct point-in-time anchor to use. #### Does the data contain inside information or personal data? No. All datasets are built entirely from publicly available information. They contain no material non-public information and no non-public personal data — the only names that appear are those in mandatory public disclosures — which keeps vendor due diligence and compliance review simple. #### What plans are available for teams? Teams and institutions are served by the Enterprise plan: custom pricing with SLAs, dedicated support, custom rate limits, and redistribution licensing. Programmatic access, meaning the REST API, Python SDK and MCP server, is part of an Enterprise agreement. Individual professionals can self-serve with the Professional plan at $199/month for the FinBrain Terminal. #### What support is available? The Professional plan includes email support. Enterprise clients get a dedicated account manager, prioritized response, and SLA-backed response times. #### What does the Enterprise plan include? Data redistribution rights, client-facing display rights, AI/LLM training rights, dedicated account management, SLA guarantees, on-premise deployment options, and white-label solutions. Enterprise plans are tailored to your team's specific requirements. #### Do you offer SLAs? Enterprise agreements include a contractual SLA covering API availability with a 99.9% monthly target and prioritized support response, backed by service credits. Professional plans receive best-effort support. #### Can we start with a professional plan and upgrade later? Yes. Institutional teams evaluate through a scoped 30-day trial with live data and a trailing 24 months of history, then move to a full Enterprise agreement. Your integrations carry over unchanged. × ## Contact Us Tell us about your team and use case. We review every inquiry and reply by email — typically within one business day. Name Work email Company Firm typeHedge Fund How do you plan to use the data? Website Send ✓ ### Thanks — your inquiry is in. Our team will review it and reach out by email shortly to set up a discovery call. Close # Price Forecasts API > API reference for the FinBrain ticker predictions endpoint. Retrieve quantitative price forecasts for a specific stock ticker. Retrieve price forecasts for a specific ticker. Returns daily or monthly forecasts with directional signals and confidence bounds, generated from ARIMA time-series models. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/predictions/{type}/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) Supports multiple authentication methods (in order of preference): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `type` | string | Yes | Prediction type: `daily` or `monthly` | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `MSFT`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | --------------------------------------- | | `apiKey` | string | No | Your API key (if not using header auth) | **Note:** Predictions are forward-looking only. The API returns forecasts from the current date forward (10 days for daily, 12 months for monthly). Historical predictions are not available. ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get daily predictions df = fb.predictions.ticker("AAPL", prediction_type="daily", as_dataframe=True) print(df) # Get monthly predictions df = fb.predictions.ticker("AAPL", prediction_type="monthly", as_dataframe=True) print(df) ``` * cURL ```bash # Get daily predictions (10 days forward) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" # Get monthly predictions (12 months forward) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/predictions/monthly/AAPL" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Get daily predictions response = requests.get( "https://api.finbrain.tech/v2/predictions/daily/AAPL", headers=headers ) data = response.json() # Get monthly predictions response = requests.get( "https://api.finbrain.tech/v2/predictions/monthly/AAPL", headers=headers ) data = response.json() ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_predictions(const std::string& symbol, const std::string& type, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/predictions/" + type + "/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_predictions("AAPL", "daily", "YOUR_API_KEY"); auto data = result["data"]; auto metadata = data["metadata"]; std::cout << "Symbol: " << data["symbol"].get() << std::endl; std::cout << "Expected Short-term: " << metadata["expectedShortTerm"].get() << "%" << std::endl; std::cout << "Expected Mid-term: " << metadata["expectedMidTerm"].get() << "%" << std::endl; std::cout << "Expected Long-term: " << metadata["expectedLongTerm"].get() << "%" << std::endl; // Iterate over predictions array for (auto& pred : data["predictions"]) { std::cout << pred["date"].get() << ": $" << pred["mid"].get() << " (" << pred["lower"].get() << " - " << pred["upper"].get() << ")" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, HeaderValue}; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct ApiResponse { success: bool, data: PredictionData, } #[derive(Debug, Deserialize)] struct PredictionData { symbol: String, name: String, #[serde(rename = "type")] pred_type: String, predictions: Vec, metadata: Metadata, #[serde(rename = "lastUpdated")] last_updated: String, } #[derive(Debug, Deserialize)] struct Prediction { date: String, mid: f64, lower: f64, upper: f64, } #[derive(Debug, Deserialize)] struct Metadata { #[serde(rename = "expectedShortTerm")] expected_short_term: f64, #[serde(rename = "expectedMidTerm")] expected_mid_term: f64, #[serde(rename = "expectedLongTerm")] expected_long_term: f64, #[serde(rename = "lowerBoundChange")] lower_bound_change: f64, #[serde(rename = "upperBoundChange")] upper_bound_change: f64, } fn get_predictions(symbol: &str, pred_type: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/predictions/{}/{}", pred_type, symbol ); let client = Client::new(); let response: ApiResponse = client .get(&url) .header(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", api_key))?) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_predictions("AAPL", "daily", "YOUR_API_KEY")?; let data = result.data; println!("Symbol: {} ({})", data.symbol, data.name); println!("Expected Short-term: {}%", data.metadata.expected_short_term); println!("Expected Long-term: {}%", data.metadata.expected_long_term); for pred in &data.predictions { println!("{}: ${:.2} (${:.2} - ${:.2})", pred.date, pred.mid, pred.lower, pred.upper); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/predictions/daily/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); console.log(result.data); ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "type": "daily", "predictions": [ { "date": "2026-01-16", "mid": 255.21, "lower": 251.01, "upper": 259.48 }, { "date": "2026-01-20", "mid": 255.59, "lower": 249.67, "upper": 261.66 }, { "date": "2026-01-21", "mid": 255.97, "lower": 248.72, "upper": 263.43 }, { "date": "2026-01-22", "mid": 256.35, "lower": 247.99, "upper": 265.00 }, { "date": "2026-01-23", "mid": 256.74, "lower": 247.39, "upper": 266.44 } ], "metadata": { "expectedShortTerm": 0.17, "expectedMidTerm": 0.47, "expectedLongTerm": 1.22, "lowerBoundChange": -3.95, "upperBoundChange": 6.67 }, "lastUpdated": "2026-01-19T15:05:59.853Z" }, "meta": { "timestamp": "2026-01-19T15:05:59.853Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | --------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | Prediction data object | | `meta` | object | Response metadata | ### Data Object Fields [Section titled “Data Object Fields”](#data-object-fields) | Field | Type | Description | | ------------- | ------ | ------------------------------------------- | | `symbol` | string | Stock ticker symbol | | `name` | string | Company name | | `type` | string | Prediction type (`daily` or `monthly`) | | `predictions` | array | Array of prediction objects | | `metadata` | object | Expected move and bound change metrics | | `lastUpdated` | string | When prediction was last updated (ISO 8601) | ### Prediction Array Items [Section titled “Prediction Array Items”](#prediction-array-items) Each item in the `predictions` array contains: | Field | Type | Description | | ------- | ------ | ------------------------------------ | | `date` | string | Forecast date (YYYY-MM-DD) | | `mid` | number | The model’s mid-point price forecast | | `lower` | number | Lower confidence bound | | `upper` | number | Upper confidence bound | ### Metadata Object Fields [Section titled “Metadata Object Fields”](#metadata-object-fields) | Field | Type | Description | | ------------------- | ------ | --------------------------------------------- | | `expectedShortTerm` | number | Expected short-term price change % (\~3 days) | | `expectedMidTerm` | number | Expected mid-term price change % (\~5 days) | | `expectedLongTerm` | number | Expected long-term price change % (\~10 days) | | `lowerBoundChange` | number | Lower bound percentage change | | `upperBoundChange` | number | Upper bound percentage change | ## Expected Move Interpretation [Section titled “Expected Move Interpretation”](#expected-move-interpretation) The expected move fields indicate percentage price change predictions: | Field | Time Horizon | | ------------------- | ----------------- | | `expectedShortTerm` | \~3 trading days | | `expectedMidTerm` | \~5 trading days | | `expectedLongTerm` | \~10 trading days | ## Usage Examples [Section titled “Usage Examples”](#usage-examples) ### Basic Prediction Lookup [Section titled “Basic Prediction Lookup”](#basic-prediction-lookup) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/predictions/daily/AAPL", headers=headers ) result = response.json() data = result["data"] metadata = data["metadata"] print(f"AAPL Prediction (updated {data['lastUpdated']})") print(f" Expected Short-term: {metadata['expectedShortTerm']}%") print(f" Expected Mid-term: {metadata['expectedMidTerm']}%") print(f" Expected Long-term: {metadata['expectedLongTerm']}%") # Iterate over predictions array for pred in data["predictions"]: print(f" {pred['date']}: ${pred['mid']:.2f} (range: ${pred['lower']:.2f} - ${pred['upper']:.2f})") ``` ### Extract Price Forecasts [Section titled “Extract Price Forecasts”](#extract-price-forecasts) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} def get_price_forecasts(symbol): """Extract price forecasts from predictions""" response = requests.get( f"https://api.finbrain.tech/v2/predictions/daily/{symbol}", headers=headers ) result = response.json() data = result["data"] for pred in data["predictions"]: print(f"{pred['date']}: ${pred['mid']:.2f} (${pred['lower']:.2f} - ${pred['upper']:.2f})") # Access bound change metrics metadata = data["metadata"] print(f"\nLower bound change: {metadata['lowerBoundChange']}%") print(f"Upper bound change: {metadata['upperBoundChange']}%") get_price_forecasts("AAPL") ``` ### Analyze Multiple Tickers [Section titled “Analyze Multiple Tickers”](#analyze-multiple-tickers) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} tickers = ["AAPL", "MSFT", "GOOGL", "NVDA"] for ticker in tickers: response = requests.get( f"https://api.finbrain.tech/v2/predictions/daily/{ticker}", headers=headers ) result = response.json() metadata = result["data"]["metadata"] print(f"{ticker}: Short {metadata['expectedShortTerm']}%, Mid {metadata['expectedMidTerm']}%, Long {metadata['expectedLongTerm']}%") ``` ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or prediction type | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Price Forecasts Dataset](/datasets/ai-forecasts/) - Use cases and analysis examples * [Available Tickers](/api-reference/available-tickers/) - Check if a ticker has predictions * [News Sentiment](/api-reference/sentiment/) - Get sentiment data for a ticker # Analyst Ratings API > API reference for the FinBrain analyst ratings endpoint. Retrieve Wall Street analyst recommendations and price targets. Retrieve Wall Street analyst ratings, price targets, and recommendation changes. Get consensus ratings and track upgrades/downgrades. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/analyst-ratings/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) Authenticate using one of the following methods (in order of recommendation): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `MSFT`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ----------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.analyst_ratings.ticker("AAPL", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/analyst-ratings/AAPL" ``` * Python (requests) ```python import requests url = "https://api.finbrain.tech/v2/analyst-ratings/AAPL" headers = {"Authorization": "Bearer YOUR_API_KEY"} params = {"startDate": "2026-01-01", "endDate": "2026-01-31"} response = requests.get(url, headers=headers, params=params) data = response.json() for r in data["data"]["ratings"]: print(f"{r['date']} - {r['institution']}: {r['rating']} (Target: {r['targetPrice']})") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_analyst_ratings(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/analyst-ratings/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_analyst_ratings("AAPL", "YOUR_API_KEY"); for (auto& r : result["data"]["ratings"]) { std::string target = r["targetPrice"].is_null() ? "N/A" : r["targetPrice"].get(); std::cout << r["date"].get() << " - " << r["institution"].get() << ": " << r["rating"].get() << " (Target: " << target << ")" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct AnalystRating { date: String, institution: String, action: String, rating: String, #[serde(rename = "targetPrice")] target_price: Option, } #[derive(Debug, Deserialize)] struct RatingsData { symbol: String, name: String, ratings: Vec, } #[derive(Debug, Deserialize)] struct Meta { timestamp: String, } #[derive(Debug, Deserialize)] struct AnalystRatingsResponse { success: bool, data: RatingsData, meta: Meta, } fn get_analyst_ratings(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/analyst-ratings/{}", symbol ); let client = Client::new(); let response: AnalystRatingsResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_analyst_ratings("AAPL", "YOUR_API_KEY")?; for r in &result.data.ratings { let target = r.target_price.as_deref().unwrap_or("N/A"); println!("{} - {}: {} (Target: {})", r.date, r.institution, r.rating, target); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/analyst-ratings/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const { data } = await response.json(); data.ratings.forEach(r => { console.log(`${r.date} - ${r.institution}: ${r.rating} (Target: ${r.targetPrice})`); }); ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "ratings": [ { "date": "2026-01-09", "institution": "Evercore ISI", "action": "Reiterated", "rating": "Outperform", "targetPrice": "$275" }, { "date": "2026-01-02", "institution": "Raymond James", "action": "Resumed", "rating": "Mkt Perform", "targetPrice": null } ] }, "meta": { "timestamp": "2026-01-19T15:06:13.918Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ----------------------------- | | `success` | boolean | Whether the request succeeded | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.ratings` | array | Array of analyst ratings | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Rating Object Fields [Section titled “Rating Object Fields”](#rating-object-fields) | Field | Type | Description | | ------------- | -------------- | ------------------------------------------------------------------- | | `date` | string | Rating date (YYYY-MM-DD) | | `institution` | string | Research firm name | | `action` | string | Type of action (Reiterated, Resumed, Upgrade, Downgrade, Initiated) | | `rating` | string | Analyst rating (Outperform, Mkt Perform, Buy, Sell, Hold, etc.) | | `targetPrice` | string or null | Price target (e.g., “$275”) or `null` if not provided | ## Rating Categories [Section titled “Rating Categories”](#rating-categories) | Rating | Signal | | ---------------------------- | ------------ | | Strong Buy | Very Bullish | | Buy / Outperform | Bullish | | Hold / Neutral / Mkt Perform | Neutral | | Underperform | Bearish | | Sell | Very Bearish | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Symbol not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Analyst Ratings Dataset](/datasets/analyst-ratings/) - Use cases and analysis examples * [News Sentiment](/api-reference/sentiment/) - News sentiment data * [Price Forecasts](/api-reference/ai-forecasts/) - Price forecasts * [Put/Call Data](/api-reference/put-call/) - Options market data # App Ratings API > API reference for the FinBrain app ratings endpoint. Retrieve per-app App Store and Play Store ratings for every app a company publishes. Retrieve mobile app ratings from Apple App Store and Google Play Store. Track app performance as alternative data for consumer-facing companies. The response carries two views of the same records: | View | Shape | Use it for | | ------ | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | `data` | One entry per date, carrying the company’s biggest app on each platform | Quick company-level reads, and clients written before `apps` existed | | `apps` | One series per app per platform, most-rated first | Anything quantitative — a company can publish many apps, and which ones matter is your judgement | Both are derived from the same underlying records, so they never disagree about which app is the biggest on a platform. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/app-ratings/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) Authenticate using one of the following methods (in order of recommendation): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `UBER`, `DASH`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of records to return (1-500). A record is one app on one date, so 500 covers a 25-app company for 20 days. Omit it for the most recent window; use `startDate`/`endDate` for history | History begins on **3 September 2026**, the day daily per-app collection started. A date range entirely before that returns an empty `data` and `apps`. An app added to the registry later starts its series on the day it was added and is never backfilled, so an app’s first `observations` date is the day FinBrain began tracking it. ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.app_ratings.ticker("UBER", date_from="2026-09-01", date_to="2026-09-30", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/app-ratings/UBER" ``` * Python (requests) ```python import requests url = "https://api.finbrain.tech/v2/app-ratings/UBER" headers = {"Authorization": "Bearer YOUR_API_KEY"} params = {"startDate": "2026-09-01", "endDate": "2026-09-30", "limit": 100} response = requests.get(url, headers=headers, params=params) data = response.json() for entry in data["data"]["data"]: # Either side is None when there is no rated app on that store ios = entry["ios"] or {} android = entry["android"] or {} print(f"{entry['date']}: iOS {ios.get('score')}, Android {android.get('score')}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_app_ratings(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/app-ratings/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_app_ratings("UBER", "YOUR_API_KEY"); // Either side is null when there is no rated app on that store for (auto& entry : result["data"]["data"]) { std::cout << entry["date"].get() << ": "; if (!entry["ios"].is_null()) std::cout << "iOS " << entry["ios"]["score"].get() << " "; if (!entry["android"].is_null()) std::cout << "Android " << entry["android"]["score"].get(); std::cout << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct IosRating { score: f64, #[serde(rename = "ratingsCount")] ratings_count: i64, } #[derive(Debug, Deserialize)] struct AndroidRating { score: f64, #[serde(rename = "ratingsCount")] ratings_count: i64, // Play Store does not always publish an install count. #[serde(rename = "installCount")] install_count: Option, } // Either side is null when the company publishes no rated app on that store. #[derive(Debug, Deserialize)] struct AppRatingEntry { date: String, ios: Option, android: Option, } #[derive(Debug, Deserialize)] struct AppRatingsInner { symbol: String, name: String, data: Vec, } #[derive(Debug, Deserialize)] struct AppRatingsResponse { success: bool, data: AppRatingsInner, } fn get_app_ratings(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/app-ratings/{}", symbol ); let client = Client::new(); let response: AppRatingsResponse = client .get(&url) .header("Authorization", format!("Bearer {}", api_key)) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_app_ratings("UBER", "YOUR_API_KEY")?; for entry in &result.data.data { let ios = entry.ios.as_ref().map(|r| r.score); let android = entry.android.as_ref().map(|r| r.score); println!("{}: iOS {:?}, Android {:?}", entry.date, ios, android); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/app-ratings/UBER", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const entry of result.data.data) { // Either side is null when there is no rated app on that store console.log( `${entry.date}: iOS ${entry.ios?.score ?? "n/a"}, ` + `Android ${entry.android?.score ?? "n/a"}` ); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "cik": "0000320193", "data": [ { "date": "2026-09-04", "ios": { "score": 4.89492, "ratingsCount": 8807114 }, "android": { "score": 4.8378, "ratingsCount": 12161409, "installCount": 844211870 } }, { "date": "2026-09-03", "ios": { "score": 4.89492, "ratingsCount": 8804809 }, "android": { "score": 4.8378, "ratingsCount": 12158128, "installCount": 844014248 } } ], "apps": [ { "platform": "android", "appId": "com.shazam.android", "appName": "Shazam: Find Music & Concerts", "observations": [ { "date": "2026-09-04", "score": 4.8378, "ratingsCount": 12161409, "installCount": 844211870 }, { "date": "2026-09-03", "score": 4.8378, "ratingsCount": 12158128, "installCount": 844014248 } ] }, { "platform": "ios", "appId": "284993459", "appName": "Shazam: Find Music & Concerts", "observations": [ { "date": "2026-09-04", "score": 4.89492, "ratingsCount": 8807114, "installCount": null }, { "date": "2026-09-03", "score": 4.89492, "ratingsCount": 8804809, "installCount": null } ] }, { "platform": "ios", "appId": "1160481993", "appName": "Apple Wallet", "observations": [ { "date": "2026-09-04", "score": 4.76624, "ratingsCount": 7382510, "installCount": null }, { "date": "2026-09-03", "score": 4.76624, "ratingsCount": 7380997, "installCount": null } ] } ] }, "meta": { "timestamp": "2026-09-04T15:06:32.888Z" } } ``` Note how `data` reports Shazam on both stores — Apple’s most-rated app on each — while `apps` goes on to Apple Wallet and the rest of the portfolio (148 apps for Apple at the time of writing). Both arrays are truncated here; `observations` runs each app’s full history over the requested date range, one entry per day. ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | Response data wrapper | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.cik` | string \| null | The company’s SEC Central Index Key, zero-padded to 10 digits. A **string**, because the leading zeros are part of the identifier. `null` for an issuer with no SEC registration, such as a non-US listing. Use it to join this dataset to Insider Trading, Corporate Lobbying, Government Contracts and Patent Filings by company: a ticker gets renamed and recycled, a CIK does not | | `data.data` | array | Blended view: one entry per date, daily (see below) | | `data.apps` | array | Per-app view: one series per app per platform, most-rated first | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### App Rating Object Fields (`data.data[]`) [Section titled “App Rating Object Fields (data.data\[\])”](#app-rating-object-fields-datadata) | Field | Type | Description | | ---------------------- | --------------- | -------------------------------------------------------------------- | | `date` | string | Date of the snapshot (YYYY-MM-DD) | | `ios` | object \| null | iOS App Store metrics, `null` when there is no rated iOS app | | `ios.score` | number | iOS App Store rating (1-5) | | `ios.ratingsCount` | integer | Number of App Store ratings | | `android` | object \| null | Google Play Store metrics, `null` when there is no rated Android app | | `android.score` | number | Google Play Store rating (1-5) | | `android.ratingsCount` | integer | Number of Play Store ratings | | `android.installCount` | integer \| null | Play Store install count, `null` when the store does not publish one | Each entry describes the company’s **biggest app on each platform** by ratings count — not a blend of everything it publishes. `ios` or `android` is `null` when the company publishes nothing on that store, or when its app there is unrated. ### App Series Object Fields (`data.apps[]`) [Section titled “App Series Object Fields (data.apps\[\])”](#app-series-object-fields-dataapps) | Field | Type | Description | | ----------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `platform` | string | `ios` or `android` | | `appId` | string \| null | App Store numeric id or Play Store package name. Every record since the 3 September 2026 restart carries one; `null` is reserved for a record without an app key and does not occur in served data | | `appName` | string \| null | App title as published on the store | | `observations` | array | That app’s own history, newest first | | `observations[].date` | string | Date of the snapshot (YYYY-MM-DD) | | `observations[].score` | number \| null | Store rating (1-5), `null` when the app is unrated | | `observations[].ratingsCount` | integer \| null | Number of ratings | | `observations[].installCount` | integer \| null | Play Store install count. Always `null` on `ios` — Apple publishes no install count | ## Working With Multiple Apps [Section titled “Working With Multiple Apps”](#working-with-multiple-apps) A company can publish many apps: Apple has over a hundred on iOS alone, and a retailer typically ships a shopping app, a payments app and a loyalty app under the same ticker. `data` answers “how is this company’s flagship app doing”; `apps` answers “what does this company publish, and how is each one doing”. We deliberately publish **no blended company score**. Weighting a portfolio of apps into one number means making a judgement — by ratings volume, by revenue relevance, by product line — that belongs to you, not to us. Every app arrives with its own series so you can filter and weight it yourself. * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Long frame: one row per app per observation apps = fb.app_ratings.ticker("AAPL", as_dataframe=True, per_app=True) # What does this company publish, and how big is each app? print(apps.groupby(["platform", "app_id", "app_name"])["ratings_count"].max()) # One app's own series shazam = apps[apps["app_id"] == "284993459"] ``` * Python (requests) ```python import requests url = "https://api.finbrain.tech/v2/app-ratings/AAPL" headers = {"Authorization": "Bearer YOUR_API_KEY"} payload = requests.get(url, headers=headers).json()["data"] for app in payload["apps"]: latest = app["observations"][0] # newest first label = app["appName"] or "unidentified app" print(f"{app['platform']:<8} {label:<30} " f"{latest['score']} ({latest['ratingsCount']} ratings)") ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/app-ratings/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const { data } = await response.json(); for (const app of data.apps) { const latest = app.observations[0]; // newest first console.log( `${app.platform} ${app.appName ?? "unidentified app"}: ` + `${latest.score} (${latest.ratingsCount} ratings)` ); } ``` ## Interpretation [Section titled “Interpretation”](#interpretation) | Rating | Quality | | --------- | ------------- | | 4.5 - 5.0 | Excellent | | 4.0 - 4.5 | Good | | 3.5 - 4.0 | Average | | 3.0 - 3.5 | Below average | | Below 3.0 | Poor | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Symbol not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [App Ratings Dataset](/datasets/app-ratings/) - Use cases and analysis examples * [LinkedIn Data](/api-reference/linkedin-data/) - Employee metrics * [News Sentiment](/api-reference/sentiment/) - News sentiment # Authentication > Technical reference for FinBrain API authentication. Learn about token-based authentication, API key management, and security best practices. All FinBrain API v2 requests require authentication using your API key. The v2 API supports multiple authentication methods for flexibility and backward compatibility. ## Authentication Methods [Section titled “Authentication Methods”](#authentication-methods) The API checks for credentials in the following order of precedence: ### 1. Authorization Header (Recommended) [Section titled “1. Authorization Header (Recommended)”](#1-authorization-header-recommended) Pass your API key as a Bearer token in the `Authorization` header: ```plaintext Authorization: Bearer YOUR_API_KEY ``` This is the recommended method for all new integrations. It keeps credentials out of URLs and is compatible with standard HTTP tooling. ### 2. X-API-Key Header [Section titled “2. X-API-Key Header”](#2-x-api-key-header) Pass your API key in the `X-API-Key` header: ```plaintext X-API-Key: YOUR_API_KEY ``` ### 3. Query Parameter [Section titled “3. Query Parameter”](#3-query-parameter) Pass your API key as the `apiKey` query parameter: ```plaintext https://api.finbrain.tech/v2/predictions/daily/AAPL?apiKey=YOUR_API_KEY ``` ### 4. Legacy Query Parameter (v1 Backward Compatibility) [Section titled “4. Legacy Query Parameter (v1 Backward Compatibility)”](#4-legacy-query-parameter-v1-backward-compatibility) The v1 `token` query parameter is still supported for backward compatibility: ```plaintext https://api.finbrain.tech/v2/predictions/daily/AAPL?token=YOUR_API_KEY ``` Caution The `token` query parameter is deprecated and may be removed in a future version. Migrate to the `Authorization` header when possible. ### Example [Section titled “Example”](#example) * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/predictions/daily/AAPL", headers=headers ) data = response.json() print(data) ``` * JavaScript ```javascript const API_KEY = "YOUR_API_KEY"; const response = await fetch( "https://api.finbrain.tech/v2/predictions/daily/AAPL", { headers: { "Authorization": `Bearer ${API_KEY}` } } ); const data = await response.json(); console.log(data); ``` ## Getting an API Key [Section titled “Getting an API Key”](#getting-an-api-key) 1. Visit [finbrain.tech](https://www.finbrain.tech) 2. Create an account or sign in 3. Navigate to your account dashboard 4. Copy your API key ## Authentication Errors [Section titled “Authentication Errors”](#authentication-errors) ### 401 Unauthorized [Section titled “401 Unauthorized”](#401-unauthorized) Returned when the API key is missing or invalid. **Response:** ```json { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Invalid or missing API key" } } ``` **Common causes:** * Missing API key in the request * Typo in the API key * Using an expired or revoked API key ### 403 Forbidden [Section titled “403 Forbidden”](#403-forbidden) Returned when the API key is valid but lacks permission for the requested resource. **Response:** ```json { "success": false, "error": { "code": "FORBIDDEN", "message": "Access denied for this resource" } } ``` **Common causes:** * Endpoint not included in your subscription tier * Account suspended * Accessing a restricted resource ### 429 Too Many Requests [Section titled “429 Too Many Requests”](#429-too-many-requests) Returned when rate limits are exceeded. **Response:** ```json { "success": false, "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "Rate limit exceeded. Please slow down." } } ``` ## Rate Limiting [Section titled “Rate Limiting”](#rate-limiting) The v2 API includes rate limit information in every response via HTTP headers: | Header | Description | | ----------------------- | -------------------------------------- | | `X-RateLimit-Limit` | Maximum requests allowed per hour | | `X-RateLimit-Remaining` | Requests remaining in current window | | `X-RateLimit-Reset` | Time when rate limit resets (ISO 8601) | **Example response headers:** ```plaintext X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 847 X-RateLimit-Reset: 2026-03-09T15:00:00Z ``` When you exceed the rate limit, the API returns a `429 Too Many Requests` response. Use the `X-RateLimit-Reset` header to determine when you can resume making requests. ### Rate Limit Tiers [Section titled “Rate Limit Tiers”](#rate-limit-tiers) | Tier | Requests/Hour | | ------------ | ------------- | | Free | 100 | | Basic | 1,000 | | Professional | 10,000 | | Enterprise | Custom | ## Security Best Practices [Section titled “Security Best Practices”](#security-best-practices) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) Never hardcode your API key. Use environment variables: * Python ```python import os import requests api_key = os.environ.get("FINBRAIN_API_KEY") headers = {"Authorization": f"Bearer {api_key}"} response = requests.get( "https://api.finbrain.tech/v2/predictions/daily/AAPL", headers=headers ) ``` * JavaScript ```javascript const API_KEY = process.env.FINBRAIN_API_KEY; const response = await fetch( "https://api.finbrain.tech/v2/predictions/daily/AAPL", { headers: { "Authorization": `Bearer ${API_KEY}` } } ); ``` * Bash ```bash export FINBRAIN_API_KEY="your_api_key_here" curl -H "Authorization: Bearer $FINBRAIN_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" ``` ### .env Files [Section titled “.env Files”](#env-files) For local development, use a `.env` file: .env ```bash FINBRAIN_API_KEY=your_api_key_here ``` Add `.env` to your `.gitignore`: .gitignore ```bash .env ``` ### Production Secrets [Section titled “Production Secrets”](#production-secrets) In production, use your platform’s secrets management: * **AWS**: Secrets Manager or Parameter Store * **Google Cloud**: Secret Manager * **Azure**: Key Vault * **Heroku**: Config Vars * **Vercel**: Environment Variables ### Additional Security Tips [Section titled “Additional Security Tips”](#additional-security-tips) 1. **Never commit API keys** to version control 2. **Don’t expose keys in client-side code** - use a backend proxy 3. **Rotate keys periodically** - especially after team member changes 4. **Use different keys** for development and production 5. **Monitor usage** - check for unexpected API call patterns 6. **Prefer header-based auth** - query parameters can leak in server logs and browser history ## Related Documentation [Section titled “Related Documentation”](#related-documentation) * [API Reference Overview](/api-reference/overview/) * [Error Codes](/api-reference/errors/) * [Quick Start](/getting-started/quickstart/) # Available Markets API > API reference for the FinBrain available markets endpoint. Retrieve a list of all supported markets and indices. Retrieve a list of all markets supported by the FinBrain API. Use this endpoint to discover available markets before querying for specific tickers. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/markets ``` ## Authentication [Section titled “Authentication”](#authentication) Authenticate using one of the following methods (in order of recommendation): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) This endpoint has no path or query parameters (aside from authentication). ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") markets = fb.available.markets(as_dataframe=True) print(markets) ``` * cURL ```bash curl "https://api.finbrain.tech/v2/markets" \ -H "Authorization: Bearer YOUR_API_KEY" ``` * Python (requests) ```python import requests response = requests.get( "https://api.finbrain.tech/v2/markets", headers={"Authorization": "Bearer YOUR_API_KEY"} ) data = response.json() for market in data["data"]["markets"]: print(f"{market['name']} ({market['region']})") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_available_markets(const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/markets"; std::string auth_header = "Authorization: Bearer " + api_key; struct curl_slist* headers = nullptr; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_available_markets("YOUR_API_KEY"); std::cout << "Available markets:" << std::endl; for (auto& market : result["data"]["markets"]) { std::cout << " - " << market["name"].get() << " (" << market["region"].get() << ")" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, HeaderValue}; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct Market { name: String, region: String, } #[derive(Debug, Deserialize)] struct MarketsData { markets: Vec, } #[derive(Debug, Deserialize)] struct MarketsResponse { success: bool, data: MarketsData, } fn get_available_markets(api_key: &str) -> Result> { let client = Client::new(); let response: MarketsResponse = client .get("https://api.finbrain.tech/v2/markets") .header(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", api_key))?) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let data = get_available_markets("YOUR_API_KEY")?; println!("Available markets:"); for market in &data.data.markets { println!(" - {} ({})", market.name, market.region); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch("https://api.finbrain.tech/v2/markets", { headers: { "Authorization": "Bearer YOUR_API_KEY" } }); const result = await response.json(); for (const market of result.data.markets) { console.log(`${market.name} (${market.region})`); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "markets": [ { "name": "S&P 500", "region": "US" }, { "name": "NASDAQ", "region": "US" }, { "name": "DOW 30", "region": "US" }, { "name": "UK FTSE 100", "region": "UK" }, { "name": "Germany DAX", "region": "DE" }, { "name": "Crypto Currencies", "region": "Global" }, { "name": "Foreign Exchange", "region": "Global" } ] }, "meta": { "timestamp": "2026-01-19T15:05:55.187Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ----------------------- | ------- | ----------------------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | Response data wrapper | | `data.markets` | array | List of available market objects | | `data.markets[].name` | string | Market name (use this value in other API calls) | | `data.markets[].region` | string | Geographic region of the market | | `meta` | object | Response metadata | | `meta.timestamp` | string | ISO 8601 timestamp of the response | ## Available Markets [Section titled “Available Markets”](#available-markets) | Market Name | Region | | ----------------- | ------------ | | DOW 30 | US | | S\&P 500 | US | | NASDAQ | US | | NYSE | US | | ETFs | US | | UK FTSE 100 | UK | | Germany DAX | DE | | Canada TSX | Canada | | Australia ASX | Australia | | HK Hang Seng | Hong Kong | | Mexico BMV | Mexico | | Foreign Exchange | Global | | Commodities | Global | | Crypto Currencies | Global | | Index Futures | Global | | Tadawul TASI | Saudi Arabia | | Russia MOEX | Russia | | Brazil BOVESPA | Brazil | | Tel Aviv TASE | Israel | | OTC Market | US | ## Usage Example [Section titled “Usage Example”](#usage-example) Use the markets endpoint to dynamically build a market selector: ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Get available markets response = requests.get("https://api.finbrain.tech/v2/markets", headers=headers) result = response.json() # Build market selector print("Available Markets:") for i, market in enumerate(result["data"]["markets"], 1): print(f" {i}. {market['name']} ({market['region']})") # Use a selected market to get tickers selected_market = result["data"]["markets"][0]["name"] tickers_resp = requests.get( "https://api.finbrain.tech/v2/tickers", headers=headers, params={"market": selected_market, "type": "daily"} ) tickers = tickers_resp.json() print(f"\n{selected_market} tickers: {len(tickers['data']['tickers'])}") ``` ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | -------------------------- | | 401 | Unauthorized | Invalid or missing API key | | 500 | Internal Server Error | Server-side error | ## Related Endpoints [Section titled “Related Endpoints”](#related-endpoints) * [Available Tickers](/api-reference/available-tickers/) - Get tickers for a market * [Market Predictions](/api-reference/market-predictions/) - Get predictions for a market # Available Tickers API > API reference for the FinBrain available tickers endpoint. Retrieve all tickers with available predictions. Retrieve a list of all tickers that have predictions available. Use query parameters to filter by prediction type, market, or region. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/tickers ``` ## Authentication [Section titled “Authentication”](#authentication) Authenticate using one of the following methods (in order of recommendation): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | --------- | ------- | -------- | ------------------------------------------------- | | `type` | string | No | Prediction type: `daily` or `monthly` | | `market` | string | No | Filter by market name (e.g., `S&P 500`, `NASDAQ`) | | `region` | string | No | Filter by region (e.g., `US`, `Global`) | | `limit` | integer | No | Limit the number of results returned | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get daily prediction tickers df = fb.available.tickers("daily", market="S&P 500", as_dataframe=True) print(df) ``` * cURL ```bash # Get all tickers with daily predictions curl "https://api.finbrain.tech/v2/tickers?type=daily" \ -H "Authorization: Bearer YOUR_API_KEY" # Filter by market curl "https://api.finbrain.tech/v2/tickers?type=daily&market=S%26P%20500" \ -H "Authorization: Bearer YOUR_API_KEY" # Filter by region with a limit curl "https://api.finbrain.tech/v2/tickers?region=US&limit=10" \ -H "Authorization: Bearer YOUR_API_KEY" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Get tickers with daily predictions response = requests.get( "https://api.finbrain.tech/v2/tickers", headers=headers, params={"type": "daily"} ) data = response.json() print(f"Daily predictions available for {len(data['data']['tickers'])} tickers") # Filter by market response = requests.get( "https://api.finbrain.tech/v2/tickers", headers=headers, params={"type": "daily", "market": "S&P 500"} ) sp500 = response.json() for t in sp500["data"]["tickers"][:5]: print(f" {t['symbol']} - {t['name']}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_available_tickers(const std::string& api_key, const std::string& type = "daily", const std::string& market = "") { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/tickers?type=" + type; if (!market.empty()) { char* encoded_market = curl_easy_escape(curl, market.c_str(), 0); url += "&market=" + std::string(encoded_market); curl_free(encoded_market); } std::string auth_header = "Authorization: Bearer " + api_key; struct curl_slist* headers = nullptr; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_available_tickers("YOUR_API_KEY", "daily", "S&P 500"); auto& tickers = result["data"]["tickers"]; std::cout << "Found " << tickers.size() << " tickers" << std::endl; // Print first 10 tickers for (size_t i = 0; i < std::min(size_t(10), tickers.size()); i++) { std::cout << " " << tickers[i]["symbol"].get() << " - " << tickers[i]["name"].get() << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, HeaderValue}; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct TickerInfo { symbol: String, name: String, } #[derive(Debug, Deserialize)] struct TickersData { tickers: Vec, } #[derive(Debug, Deserialize)] struct TickersResponse { success: bool, data: TickersData, } fn get_available_tickers( api_key: &str, pred_type: &str, market: Option<&str>, ) -> Result> { let mut url = format!( "https://api.finbrain.tech/v2/tickers?type={}", pred_type ); if let Some(m) = market { url.push_str(&format!("&market={}", urlencoding::encode(m))); } let client = Client::new(); let response: TickersResponse = client .get(&url) .header(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", api_key))?) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let data = get_available_tickers("YOUR_API_KEY", "daily", Some("S&P 500"))?; println!("Found {} tickers", data.data.tickers.len()); // Print first 10 tickers for ticker_info in data.data.tickers.iter().take(10) { println!(" {} - {}", ticker_info.symbol, ticker_info.name); } Ok(()) } ``` * JavaScript ```javascript // Get daily tickers const response = await fetch( "https://api.finbrain.tech/v2/tickers?type=daily", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); console.log(`Found ${result.data.tickers.length} tickers`); console.log(result.data.tickers[0]); // { symbol: "AAPL", name: "Apple Inc." } // Filter by market const sp500 = await fetch( "https://api.finbrain.tech/v2/tickers?type=daily&market=" + encodeURIComponent("S&P 500"), { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const sp500Data = await sp500.json(); console.log(`S&P 500 tickers: ${sp500Data.data.tickers.length}`); ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "tickers": [ { "symbol": "AAPL", "name": "Apple Inc." }, { "symbol": "MSFT", "name": "Microsoft Corp." }, { "symbol": "GOOGL", "name": "Alphabet Inc." } ] }, "meta": { "timestamp": "2026-01-19T15:05:55.187Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ----------------------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | Response data wrapper | | `data.tickers` | array | List of ticker objects | | `data.tickers[].symbol` | string | Ticker symbol | | `data.tickers[].name` | string | Company or asset name | | `meta` | object | Response metadata | | `meta.timestamp` | string | ISO 8601 timestamp of the response | ## Prediction Types [Section titled “Prediction Types”](#prediction-types) | Type | Description | Forecast Horizon | | --------- | ------------------------- | ---------------- | | `daily` | Daily price predictions | 10 trading days | | `monthly` | Monthly price predictions | 12 months | ## Usage Examples [Section titled “Usage Examples”](#usage-examples) ### Check Ticker Availability [Section titled “Check Ticker Availability”](#check-ticker-availability) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} def is_ticker_available(ticker, pred_type="daily"): """Check if a ticker has predictions available""" response = requests.get( "https://api.finbrain.tech/v2/tickers", headers=headers, params={"type": pred_type} ) tickers = response.json()["data"]["tickers"] symbols = [t["symbol"] for t in tickers] return ticker.upper() in symbols # Check if AAPL has daily predictions if is_ticker_available("AAPL", "daily"): print("AAPL has daily predictions available") else: print("AAPL does not have predictions") ``` ### Build Ticker Universe [Section titled “Build Ticker Universe”](#build-ticker-universe) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Get S&P 500 tickers directly via query parameter response = requests.get( "https://api.finbrain.tech/v2/tickers", headers=headers, params={"type": "daily", "market": "S&P 500"} ) sp500_tickers = response.json()["data"]["tickers"] print(f"S&P 500 tickers: {len(sp500_tickers)}") # Filter for specific tickers from results tech_symbols = {"AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META"} tech_tickers = [t for t in sp500_tickers if t["symbol"] in tech_symbols] print(f"Tech universe: {[t['symbol'] for t in tech_tickers]}") ``` ### Cross-Reference with Watchlist [Section titled “Cross-Reference with Watchlist”](#cross-reference-with-watchlist) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} watchlist = ["AAPL", "MSFT", "XYZ123", "GOOGL", "INVALID"] # Get available tickers response = requests.get( "https://api.finbrain.tech/v2/tickers", headers=headers, params={"type": "daily"} ) tickers_data = response.json()["data"]["tickers"] available = set(t["symbol"] for t in tickers_data) # Find which watchlist items are available valid = [t for t in watchlist if t in available] invalid = [t for t in watchlist if t not in available] print(f"Valid tickers: {valid}") print(f"Invalid tickers: {invalid}") ``` ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid prediction type or query parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related Endpoints [Section titled “Related Endpoints”](#related-endpoints) * [Available Markets](/api-reference/available-markets/) - Get available markets * [Price Forecasts](/api-reference/ai-forecasts/) - Get forecasts for a ticker * [Market Predictions](/api-reference/market-predictions/) - Get predictions for a market # Congressional Trading API > API reference for the FinBrain congressional trading endpoints. Retrieve US House and Senate trading activity data. Retrieve stock trading activity from US House Representatives and Senators disclosed under the STOCK Act. House and Senate trades are served by separate endpoints with an identical schema. ## Endpoints [Section titled “Endpoints”](#endpoints) ```plaintext GET /v2/congress/house/{symbol} GET /v2/congress/senate/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) The API supports multiple authentication methods: | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `NVDA`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ----------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return | `startDate` and `endDate` filter on the transaction `date`, not on `disclosureDate`. A trade executed inside the window is returned even if it was disclosed after `endDate`. ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") house_df = fb.house_trades.ticker("NVDA", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) senate_df = fb.senate_trades.ticker("NVDA", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(house_df) print(senate_df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/congress/house/AAPL" curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/congress/senate/AAPL" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} for chamber in ["house", "senate"]: response = requests.get( f"https://api.finbrain.tech/v2/congress/{chamber}/AAPL", headers=headers, params={"limit": 10} ) data = response.json() for t in data["data"]["trades"]: disclosed = t["disclosureDate"] or "not disclosed" owner = t["owner"] or "?" print(f"{t['date']} - {t['politician']} ({chamber}, {owner}): " f"{t['transactionType']} ({t['amount']}) disclosed {disclosed}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_congress_trades(const std::string& chamber, const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/congress/" + chamber + "/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { for (const std::string& chamber : {"house", "senate"}) { auto result = get_congress_trades(chamber, "AAPL", "YOUR_API_KEY"); for (auto& t : result["data"]["trades"]) { std::string disclosed = t["disclosureDate"].is_null() ? "not disclosed" : t["disclosureDate"].get(); std::cout << t["date"].get() << " - " << t["politician"].get() << " (" << chamber << "): " << t["transactionType"].get() << " (" << t["amount"].get() << ")" << " disclosed " << disclosed << std::endl; } } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct CongressTrade { date: String, politician: String, #[serde(rename = "transactionType")] transaction_type: String, amount: String, owner: Option, #[serde(rename = "amountRaw")] amount_raw: Option, #[serde(rename = "amountFlag")] amount_flag: Option, #[serde(rename = "disclosureDate")] disclosure_date: Option, } #[derive(Debug, Deserialize)] struct CongressData { symbol: String, name: String, chamber: String, trades: Vec, } #[derive(Debug, Deserialize)] struct CongressTradesResponse { success: bool, data: CongressData, } fn get_congress_trades(chamber: &str, symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/congress/{}/{}", chamber, symbol ); let client = Client::new(); let response: CongressTradesResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { for chamber in ["house", "senate"] { let result = get_congress_trades(chamber, "AAPL", "YOUR_API_KEY")?; for t in &result.data.trades { let disclosed = t.disclosure_date.as_deref().unwrap_or("not disclosed"); println!("{} - {} ({}): {} ({}) disclosed {}", t.date, t.politician, chamber, t.transaction_type, t.amount, disclosed); } } Ok(()) } ``` * JavaScript ```javascript for (const chamber of ["house", "senate"]) { const response = await fetch( `https://api.finbrain.tech/v2/congress/${chamber}/AAPL`, { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const t of result.data.trades) { const disclosed = t.disclosureDate ?? "not disclosed"; console.log(`${t.date} - ${t.politician} (${chamber}): ${t.transactionType} (${t.amount}) disclosed ${disclosed}`); } } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "chamber": "house", "trades": [ { "date": "2025-11-24", "politician": "Debbie Dingell", "transactionType": "Sale", "amount": "$50,001 - $100,000", "owner": "SELF", "amountRaw": null, "amountFlag": null, "disclosureDate": "2025-12-16" }, { "date": "2024-03-11", "politician": "Debbie Dingell", "transactionType": "Purchase", "amount": "$1,001 - $15,000", "owner": "SP", "amountRaw": "$1,001-15,000", "amountFlag": null, "disclosureDate": "2024-04-05" } ] }, "meta": { "timestamp": "2026-01-19T15:06:31.764Z" } } ``` The Senate endpoint returns the same structure with `"chamber": "senate"`. ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ------------------------------------------- | | `success` | boolean | Whether the request was successful | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.chamber` | string | Congressional chamber (`house` or `senate`) | | `data.trades` | array | Array of trade objects | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Trade Object Fields [Section titled “Trade Object Fields”](#trade-object-fields) | Field | Type | Description | | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `date` | string | Transaction date (YYYY-MM-DD) | | `politician` | string | Name of the House or Senate member | | `transactionType` | string | Transaction type (Purchase or Sale) | | `amount` | string | Transaction amount (exact value or range), normalized to the statutory STOCK Act brackets where possible — see [Amount Ranges](#amount-ranges) | | `owner` | string or null | Beneficial owner of the account: `SELF` (the member’s own account), `SP` (spouse), `DC` (dependent child), `JT` (joint), or a member-specific account code. Senate filings that leave the owner column blank report `UNKNOWN`; House filings that leave it blank report `SELF`, per the House PTR-form instructions | | `amountRaw` | string or null | The amount string as originally filed — set only when `amount` was rewritten to a canonical bracket, `null` when the filed value was already canonical | | `amountFlag` | string or null | `null` on clean rows; `review` when the filed amount was unusable, `ambiguous` when it had two defensible readings (in both cases `amount` keeps the raw string as filed) | | `disclosureDate` | string or null | Date the trade was publicly disclosed in the periodic transaction report (YYYY-MM-DD). The STOCK Act allows up to 45 days, so this is the correct point-in-time anchor for backtesting. Nullable, but nulls are rare — historical rows were backfilled | ## Amount Ranges [Section titled “Amount Ranges”](#amount-ranges) `amount` is normalized to the statutory STOCK Act brackets below whenever the filed string is an unambiguous formatting variant of one; the original filed string is preserved in `amountRaw`. Open-ended filing categories (`"Over $1,000,000"`, `"Under $1,000"`, `"Over $50,000,000"`) and exact values are kept as filed. A filing whose amount could not be read reports `amount` as `"Unknown"` with `amountFlag` set to `review`. | Range | Min | Max | | ----------------------- | ---------- | ---------- | | $1,001 - $15,000 | $1,001 | $15,000 | | $15,001 - $50,000 | $15,001 | $50,000 | | $50,001 - $100,000 | $50,001 | $100,000 | | $100,001 - $250,000 | $100,001 | $250,000 | | $250,001 - $500,000 | $250,001 | $500,000 | | $500,001 - $1,000,000 | $500,001 | $1,000,000 | | $1,000,001 - $5,000,000 | $1,000,001 | $5,000,000 | | Over $5,000,000 | $5,000,001 | N/A | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Congressional Trading Dataset](/datasets/congressional-trading/) - Use cases and analysis examples * [Screener API](/api-reference/screener/) - Screen congressional trades across tickers * [Insider Transactions](/api-reference/insider-transactions/) - SEC Form 4 data * [Price Forecasts](/api-reference/ai-forecasts/) - Price forecasts # Corporate Lobbying API > API reference for the FinBrain corporate lobbying endpoint. Retrieve lobbying disclosure filings with registrant details, expenditures, and issue codes. Retrieve corporate lobbying filings from US Senate LDA (Lobbying Disclosure Act) disclosures. Track which firms lobby on behalf of a company, how much they spend, and which policy areas and government entities they target. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/lobbying/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) The API supports multiple authentication methods: | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `MSFT`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ------------------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return (1-500) | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.corporate_lobbying.ticker("AAPL", date_from="2025-01-01", date_to="2025-12-31", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/lobbying/AAPL" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/lobbying/AAPL", headers=headers, params={"limit": 10} ) data = response.json() for f in data["data"]["filings"]: print(f"{f['date']} {f['quarter']}: {f['registrantName']} " f"- ${f['income']:,.0f} income, ${f['expenses']:,.0f} expenses") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_corporate_lobbying(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/lobbying/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_corporate_lobbying("AAPL", "YOUR_API_KEY"); for (auto& f : result["data"]["filings"]) { std::cout << f["date"].get() << " " << f["quarter"].get() << ": " << f["registrantName"].get() << " - $" << f["income"].get() << " income, $" << f["expenses"].get() << " expenses" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct Filing { date: String, #[serde(rename = "filingUuid")] filing_uuid: String, #[serde(rename = "filingYear")] filing_year: i32, quarter: String, #[serde(rename = "clientName")] client_name: String, #[serde(rename = "registrantName")] registrant_name: String, income: f64, expenses: f64, #[serde(rename = "issueCodes")] issue_codes: Vec, #[serde(rename = "governmentEntities")] government_entities: Vec, } #[derive(Debug, Deserialize)] struct LobbyingData { symbol: String, name: String, filings: Vec, } #[derive(Debug, Deserialize)] struct LobbyingResponse { success: bool, data: LobbyingData, } fn get_corporate_lobbying(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/lobbying/{}", symbol ); let client = Client::new(); let response: LobbyingResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_corporate_lobbying("AAPL", "YOUR_API_KEY")?; for f in &result.data.filings { println!("{} {}: {} - ${} income, ${} expenses", f.date, f.quarter, f.registrant_name, f.income, f.expenses); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/lobbying/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const f of result.data.filings) { console.log(`${f.date} ${f.quarter}: ${f.registrantName} - $${f.income} income, $${f.expenses} expenses`); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "filings": [ { "date": "2025-09-15", "filingUuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "filingYear": 2025, "quarter": "Q3", "clientName": "Apple Inc.", "registrantName": "Fierce Government Relations", "income": 150000, "expenses": 0, "issueCodes": ["TAX", "TRD", "COM"], "governmentEntities": ["Senate", "House"], "cik": "0000320193" } ] }, "meta": { "timestamp": "2026-03-12T12:00:00.000Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.filings` | array | Array of lobbying filing objects | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Filing Object Fields [Section titled “Filing Object Fields”](#filing-object-fields) | Field | Type | Description | | -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `date` | string | Public posting date of the filing (YYYY-MM-DD) — the point-in-time anchor; the reporting period is in `filingYear` and `quarter` | | `filingUuid` | string | Unique filing identifier | | `filingYear` | integer | Year of the filing | | `quarter` | string | Filing quarter (Q1, Q2, Q3, Q4) | | `clientName` | string | Company being represented | | `registrantName` | string | Lobbying firm name | | `income` | number | Income reported by the registrant (USD) | | `expenses` | number | Expenses reported by the registrant (USD) | | `issueCodes` | array | Policy area codes (e.g., TAX, TRD, COM) | | `governmentEntities` | array | Government bodies engaged (e.g., Senate, House) | | `cik` | string \| null | SEC Central Index Key of the company as of this record — 10-digit zero-padded string, `null` when unresolved. Delivered for joining to your own SEC-keyed data; the API cannot be queried by CIK | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Corporate Lobbying Dataset](/datasets/corporate-lobbying/) - Use cases and analysis examples * [Stock Screener API](/api-reference/screener/) - Screen lobbying data across tickers * [Insider Transactions](/api-reference/insider-transactions/) - Insider trading data * [Congressional Trading](/api-reference/congressional-trading/) - Congressional trading data # Error Codes > Complete reference of FinBrain API error codes, their meanings, and how to handle them in your application. This page documents all error codes returned by the FinBrain API and how to handle them in your application. ## Error Response Format [Section titled “Error Response Format”](#error-response-format) All errors are returned as JSON with the following envelope structure: ```json { "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable error message", "details": { } } } ``` The `details` object may contain additional context depending on the error type. For example, a validation error may include the specific fields that failed validation. ## HTTP Status Codes [Section titled “HTTP Status Codes”](#http-status-codes) ### 400 Bad Request [Section titled “400 Bad Request”](#400-bad-request) The request is malformed or contains invalid parameters. ```json { "success": false, "error": { "code": "BAD_REQUEST", "message": "Invalid ticker symbol: XYZ123", "details": { } } } ``` The `VALIDATION_ERROR` code is also returned with a 400 status when specific input fields fail validation: ```json { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Invalid value for parameter 'type'. Expected 'daily' or 'monthly'.", "details": { "field": "type", "expected": ["daily", "monthly"] } } } ``` **Python SDK Exception:** `BadRequest` **Common causes:** * Invalid ticker symbol * Invalid market identifier * Invalid prediction type (not `daily` or `monthly`) * Malformed date parameters **How to fix:** * Verify the ticker symbol exists using `/available/tickers` * Check the market name using `/available/markets` * Ensure dates are in YYYY-MM-DD format ### 401 Unauthorized [Section titled “401 Unauthorized”](#401-unauthorized) API key missing or invalid. ```json { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Invalid or missing API key", "details": { } } } ``` **Python SDK Exception:** `AuthenticationError` **Common causes:** * Missing `token` query parameter * Invalid API key * Expired API key * Typo in API key **How to fix:** * Ensure the `token` parameter is included in every request * Verify your API key is correct * Check your account dashboard for key status ### 403 Forbidden [Section titled “403 Forbidden”](#403-forbidden) Authenticated, but not authorised to perform this action. ```json { "success": false, "error": { "code": "FORBIDDEN", "message": "Access denied for this resource", "details": { } } } ``` **Python SDK Exception:** `PermissionDenied` **Common causes:** * Endpoint not included in your subscription tier * Account suspended * Accessing a premium endpoint with a free tier key **How to fix:** * Check your subscription tier and available endpoints * Upgrade your subscription if needed * Contact support if you believe this is an error ### 404 Not Found [Section titled “404 Not Found”](#404-not-found) Requested data or endpoint not found. ```json { "success": false, "error": { "code": "NOT_FOUND", "message": "Ticker INVALID not found in market S&P 500", "details": { } } } ``` **Python SDK Exception:** `NotFound` **Common causes:** * Ticker doesn’t exist in the specified market * Endpoint path is incorrect * Data not available for the specified date range **How to fix:** * Verify the ticker exists using `/available/tickers` * Check the endpoint path in the API reference * Try a different date range ### 405 Method Not Allowed [Section titled “405 Method Not Allowed”](#405-method-not-allowed) Endpoint exists, but the HTTP method is not supported. ```json { "success": false, "error": { "code": "METHOD_NOT_ALLOWED", "message": "POST method not supported for this endpoint", "details": { } } } ``` **Python SDK Exception:** `MethodNotAllowed` **Common causes:** * Using POST instead of GET * Using PUT, DELETE, or PATCH on read-only endpoints **How to fix:** * All FinBrain API endpoints use GET requests * Change your HTTP method to GET ### 429 Too Many Requests [Section titled “429 Too Many Requests”](#429-too-many-requests) You have exceeded the rate limit for your subscription tier. ```json { "success": false, "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "Rate limit exceeded. Please retry after 30 seconds.", "details": { "retryAfter": 30 } } } ``` **Python SDK Exception:** `RateLimitExceeded` **Common causes:** * Sending too many requests in a short time window * Exceeding your plan’s requests-per-minute quota * Running parallel requests without throttling **How to fix:** * Check the `X-RateLimit-Remaining` header before sending requests * Implement exponential backoff when you receive a 429 * Wait until the time indicated by the `X-RateLimit-Reset` header * Upgrade your subscription for higher rate limits ### 500 Internal Server Error [Section titled “500 Internal Server Error”](#500-internal-server-error) Internal error on FinBrain’s side. Retrying later may help. ```json { "success": false, "error": { "code": "INTERNAL_ERROR", "message": "An unexpected error occurred", "details": { } } } ``` **Python SDK Exception:** `ServerError` **Common causes:** * Server-side issues * Database connectivity problems * Temporary service disruption **How to fix:** * Retry the request after a short delay * Check FinBrain status page for outages * Contact support if the issue persists ## Rate Limiting [Section titled “Rate Limiting”](#rate-limiting) The FinBrain v2 API includes rate limiting headers on every response, regardless of status code. Use these headers to monitor your usage and avoid hitting limits. | Header | Description | | ----------------------- | ------------------------------------------------------------------ | | `X-RateLimit-Limit` | Maximum number of requests allowed in the current time window | | `X-RateLimit-Remaining` | Number of requests remaining in the current time window | | `X-RateLimit-Reset` | Unix timestamp (seconds) when the current rate limit window resets | **Example response headers:** ```plaintext HTTP/1.1 200 OK X-RateLimit-Limit: 100 X-RateLimit-Remaining: 87 X-RateLimit-Reset: 1706400000 ``` When `X-RateLimit-Remaining` reaches `0`, subsequent requests will return a `429` status with the `RATE_LIMIT_EXCEEDED` error code until the window resets. ## Error Handling Examples [Section titled “Error Handling Examples”](#error-handling-examples) * Python ```python from finbrain import FinBrainClient from finbrain.exceptions import ( AuthenticationError, NotFound, RateLimitExceeded, ServerError, FinBrainError ) import time fb = FinBrainClient(api_key="YOUR_API_KEY") def get_predictions_with_retry(ticker, max_retries=3): """Get predictions with automatic retry on failure""" for attempt in range(max_retries): try: return fb.predictions.ticker(ticker, prediction_type="daily") except AuthenticationError: # Auth error - don't retry raise Exception("Invalid API key") except NotFound: # Not found - don't retry raise Exception(f"Ticker {ticker} not found") except RateLimitExceeded as e: # Rate limited - wait and retry wait_time = e.retry_after or (2 ** attempt) print(f"Rate limited. Retrying in {wait_time}s...") time.sleep(wait_time) except ServerError: # Server error - retry with backoff if attempt == max_retries - 1: raise wait_time = 2 ** attempt print(f"Server error. Retrying in {wait_time}s...") time.sleep(wait_time) except FinBrainError: # Other API error - retry if attempt == max_retries - 1: raise time.sleep(1) raise Exception("Max retries exceeded") # Usage try: data = get_predictions_with_retry("AAPL") print(data) except Exception as e: print(f"Error: {e}") ``` * JavaScript ```javascript const API_KEY = "YOUR_API_KEY"; async function getPredictionsWithRetry(ticker, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { const response = await fetch( `https://api.finbrain.tech/v2/ticker/${ticker}/predictions/daily?token=${API_KEY}` ); if (response.ok) { return await response.json(); } if (response.status === 401) { throw new Error("Invalid API key"); } if (response.status === 404) { throw new Error(`Ticker ${ticker} not found`); } if (response.status === 429) { // Rate limited - use reset header or backoff const resetTime = response.headers.get("X-RateLimit-Reset"); const waitTime = resetTime ? Math.max(0, resetTime * 1000 - Date.now()) : Math.pow(2, attempt) * 1000; console.log(`Rate limited. Retrying in ${Math.ceil(waitTime / 1000)}s...`); await new Promise(resolve => setTimeout(resolve, waitTime)); continue; } if (response.status === 500) { // Server error - retry with backoff if (attempt === maxRetries - 1) { throw new Error("Server error"); } const waitTime = Math.pow(2, attempt) * 1000; console.log(`Server error. Retrying in ${waitTime}ms...`); await new Promise(resolve => setTimeout(resolve, waitTime)); continue; } // Other error - don't retry throw new Error(`HTTP ${response.status}`); } catch (error) { if (attempt === maxRetries - 1) { throw error; } } } throw new Error("Max retries exceeded"); } // Usage try { const data = await getPredictionsWithRetry("AAPL"); console.log(data); } catch (error) { console.error("Error:", error.message); } ``` ## Python SDK Exception Classes [Section titled “Python SDK Exception Classes”](#python-sdk-exception-classes) The Python SDK provides typed exceptions for each error code: | Exception | HTTP Status | Error Code | Description | | --------------------- | ----------- | --------------------------------- | ----------------------------------------------------------------------- | | `BadRequest` | 400 | `BAD_REQUEST`, `VALIDATION_ERROR` | The request is malformed or contains invalid parameters | | `AuthenticationError` | 401 | `UNAUTHORIZED` | API key missing or invalid | | `PermissionDenied` | 403 | `FORBIDDEN` | Authenticated, but not authorised to perform this action | | `NotFound` | 404 | `NOT_FOUND` | Requested data or endpoint not found | | `MethodNotAllowed` | 405 | `METHOD_NOT_ALLOWED` | Endpoint exists, but the HTTP method is not supported | | `RateLimitExceeded` | 429 | `RATE_LIMIT_EXCEEDED` | Too many requests; slow down or wait for the rate limit window to reset | | `ServerError` | 500 | `INTERNAL_ERROR` | Internal error on FinBrain’s side | | `InvalidResponse` | N/A | N/A | Response couldn’t be parsed as JSON | | `FinBrainError` | N/A | N/A | Base class for all SDK exceptions | ## Best Practices [Section titled “Best Practices”](#best-practices) 1. **Always check status codes** - Don’t assume success; inspect the `success` field in every response 2. **Implement retry logic** - Use exponential backoff for 429 and 500 errors 3. **Respect rate limits** - Monitor `X-RateLimit-Remaining` and pause before hitting zero 4. **Cache responses** - Reduce API calls by caching data locally 5. **Validate inputs** - Check ticker symbols before making requests 6. **Handle errors gracefully** - Provide meaningful error messages to users 7. **Parse the error envelope** - Use the `error.code` field for programmatic error handling and `error.message` for user-facing output ## Related Documentation [Section titled “Related Documentation”](#related-documentation) * [Authentication](/api-reference/authentication/) * [API Reference Overview](/api-reference/overview/) * [Python SDK](/integrations/python/) # Government Contracts API > API reference for the FinBrain government contracts endpoint. Retrieve federal contract awards with agency details, NAICS codes, and award amounts from USAspending.gov data. Retrieve federal government contract awards from USAspending.gov mapped to stock tickers. Track contract values, awarding agencies, industry classifications, and contract periods. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/government-contracts/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) The API supports multiple authentication methods: | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ---------------------------------------- | | `symbol` | string | Yes | Stock ticker symbol (e.g., `LMT`, `RTX`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ------------------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return (1-500) | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.government_contracts.ticker("LMT", date_from="2025-01-01", date_to="2025-12-31", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/government-contracts/LMT" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/government-contracts/LMT", headers=headers, params={"limit": 10} ) data = response.json() for c in data["data"]["contracts"]: print(f"{c['startDate']}: ${c['awardAmount']:,.0f} " f"from {c['awardingAgency']} — {c['description']}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_government_contracts(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/government-contracts/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_government_contracts("LMT", "YOUR_API_KEY"); for (auto& c : result["data"]["contracts"]) { std::cout << c["startDate"].get() << ": $" << c["awardAmount"].get() << " from " << c["awardingAgency"].get() << " — " << c["description"].get() << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct Contract { #[serde(rename = "awardId")] award_id: String, #[serde(rename = "awardAmount")] award_amount: f64, #[serde(rename = "awardType")] award_type: String, #[serde(rename = "awardingAgency")] awarding_agency: String, #[serde(rename = "awardingSubAgency")] awarding_sub_agency: String, #[serde(rename = "recipientName")] recipient_name: String, #[serde(rename = "startDate")] start_date: String, #[serde(rename = "endDate")] end_date: String, description: String, #[serde(rename = "naicsCode")] naics_code: String, #[serde(rename = "naicsDescription")] naics_description: String, #[serde(rename = "contractAwardType")] contract_award_type: String, } #[derive(Debug, Deserialize)] struct ContractData { symbol: String, name: String, contracts: Vec, } #[derive(Debug, Deserialize)] struct ContractResponse { success: bool, data: ContractData, } fn get_government_contracts(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/government-contracts/{}", symbol ); let client = Client::new(); let response: ContractResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_government_contracts("LMT", "YOUR_API_KEY")?; for c in &result.data.contracts { println!("{}: ${} from {} — {}", c.start_date, c.award_amount, c.awarding_agency, c.description); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/government-contracts/LMT", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const c of result.data.contracts) { console.log(`${c.startDate}: $${c.awardAmount.toLocaleString()} from ${c.awardingAgency} — ${c.description}`); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "LMT", "name": "Lockheed Martin Corporation", "contracts": [ { "awardId": "CONT_AWD_0001", "awardAmount": 50000000, "awardType": "", "awardingAgency": "Department of Defense", "awardingSubAgency": "Department of the Army", "recipientName": "Lockheed Martin Corporation", "startDate": "2025-06-01", "endDate": "2026-06-01", "description": "Aircraft maintenance services", "naicsCode": "336411", "naicsDescription": "Aircraft Manufacturing", "contractAwardType": "", "cik": "0000936468" } ] }, "meta": { "timestamp": "2026-03-12T12:00:00.000Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.contracts` | array | Array of contract award objects | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Contract Object Fields [Section titled “Contract Object Fields”](#contract-object-fields) | Field | Type | Description | | ------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `awardId` | string | Unique federal award identifier (records are deduplicated and updated by this key) | | `awardAmount` | number | Total award value in USD, reflecting the latest reported state of the award | | `awardType` | string | Present in the schema but not populated by the source award endpoint (empty string) | | `awardingAgency` | string | Federal agency issuing the contract | | `awardingSubAgency` | string | Sub-agency within the awarding agency | | `recipientName` | string | Company receiving the contract | | `startDate` | string | Period-of-performance start date (YYYY-MM-DD) — the recommended point-in-time anchor for backtests | | `endDate` | string | Period-of-performance end date (YYYY-MM-DD); may be empty for indefinite-delivery awards | | `description` | string | Plain-text description of the contract scope | | `naicsCode` | string | NAICS industry classification code | | `naicsDescription` | string | Human-readable NAICS description — use this for sector/category classification | | `contractAwardType` | string | Present in the schema but not populated by the source award endpoint (empty string) | | `cik` | string \| null | SEC Central Index Key of the company as of this record — 10-digit zero-padded string, `null` when unresolved. Delivered for joining to your own SEC-keyed data; the API cannot be queried by CIK | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Government Contracts Dataset](/datasets/government-contracts/) - Use cases and analysis examples * [Stock Screener API](/api-reference/screener/) - Screen government contracts across tickers * [Corporate Lobbying API](/api-reference/corporate-lobbying/) - Corporate lobbying data * [Insider Transactions API](/api-reference/insider-transactions/) - Insider trading data # Insider Transactions API > API reference for the FinBrain insider transactions endpoint. Retrieve SEC Form 4 insider trading data for stock tickers. Retrieve insider trading data from SEC Form 4 filings. Track executive purchases, sales, option exercises, and ownership changes for any ticker. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/insider-trading/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) The API supports multiple authentication methods: | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `MSFT`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ----------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.insider_transactions.ticker("AAPL", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/insider-trading/AAPL" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/insider-trading/AAPL", headers=headers, params={"limit": 10} ) data = response.json() for t in data["data"]["transactions"]: print(f"{t['date']} - {t['insider']}: {t['transactionType']} " f"({t['shares']} shares @ ${t['pricePerShare']:.2f})") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_insider_transactions(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/insider-trading/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_insider_transactions("AAPL", "YOUR_API_KEY"); for (auto& t : result["data"]["transactions"]) { std::cout << t["date"].get() << " - " << t["insider"].get() << ": " << t["transactionType"].get() << " (" << t["shares"].get() << " shares @ $" << t["pricePerShare"].get() << ")" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct Transaction { date: String, insider: String, relationship: String, #[serde(rename = "transactionType")] transaction_type: String, shares: i64, #[serde(rename = "pricePerShare")] price_per_share: f64, #[serde(rename = "totalValue")] total_value: i64, #[serde(rename = "sharesOwned")] shares_owned: i64, #[serde(rename = "filingUrl")] filing_url: String, } #[derive(Debug, Deserialize)] struct InsiderData { symbol: String, name: String, transactions: Vec, } #[derive(Debug, Deserialize)] struct InsiderResponse { success: bool, data: InsiderData, } fn get_insider_transactions(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/insider-trading/{}", symbol ); let client = Client::new(); let response: InsiderResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_insider_transactions("AAPL", "YOUR_API_KEY")?; for t in &result.data.transactions { println!("{} - {}: {} ({} shares @ ${:.2})", t.date, t.insider, t.transaction_type, t.shares, t.price_per_share); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/insider-trading/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const t of result.data.transactions) { console.log(`${t.date} - ${t.insider}: ${t.transactionType} (${t.shares} shares @ $${t.pricePerShare})`); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "transactions": [ { "date": "2026-06-15", "insider": "Ben Borders", "relationship": "Principal Accounting Officer", "transactionType": "Sale", "shares": 116, "pricePerShare": 295.14, "totalValue": 34236, "sharesOwned": 38713, "filingDate": "2026-06-17", "filingUrl": "https://www.sec.gov/Archives/edgar/data/2100523/000114036126025620", "cik": "0000320193" } ] }, "meta": { "timestamp": "2026-01-19T15:06:21.699Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ------------------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.transactions` | array | Array of transaction objects | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Transaction Object Fields [Section titled “Transaction Object Fields”](#transaction-object-fields) | Field | Type | Description | | ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `date` | string | Transaction date (YYYY-MM-DD) | | `insider` | string | Insider name | | `relationship` | string | Insider’s role/relationship | | `transactionType` | string | Type of transaction (see Transaction Types below) | | `shares` | integer | Number of shares | | `pricePerShare` | number | Transaction price per share | | `totalValue` | integer | Total transaction value in USD | | `sharesOwned` | integer | Total shares owned after transaction | | `filingDate` | string | Date the Form 4 was filed with the SEC and became public (YYYY-MM-DD). SEC rules require filing within 2 business days of the transaction, so this is the correct point-in-time anchor for backtesting | | `filingUrl` | string | Link to SEC Form 4 filing | | `cik` | string \| null | SEC Central Index Key of the company as of this record — 10-digit zero-padded string, `null` when unresolved. Delivered for joining to your own SEC-keyed data; the API cannot be queried by CIK | ## Transaction Types [Section titled “Transaction Types”](#transaction-types) | Type | Description | | -------------------- | --------------------------------- | | Purchase | Open market buy | | Sale | Open market sell | | Derivative\_Purchase | Derivative security buy | | Derivative\_Sale | Derivative security sell | | Exercise | Option/warrant exercise | | Award | Grant/award from company | | Gift | Shares donated | | Tax | Tax withholding on vesting | | Conversion | Security conversion (NASDAQ only) | | Other\_Acquisition | Other share acquisition | | Other\_Disposition | Other share disposition | These can be grouped for analysis: * **Acquisitions**: Purchase, Derivative\_Purchase, Exercise, Award, Other\_Acquisition * **Dispositions**: Sale, Derivative\_Sale, Tax, Gift, Other\_Disposition * **Neutral**: Conversion ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Insider Transactions Dataset](/datasets/insider-transactions/) - Use cases and analysis examples * [Congressional Trading](/api-reference/congressional-trading/) - US House and Senate trading data * [Price Forecasts](/api-reference/ai-forecasts/) - Price forecasts # LinkedIn Data API > API reference for the FinBrain LinkedIn data endpoint. Retrieve employee count and follower metrics as alternative data. Retrieve LinkedIn employee counts, follower metrics, and job postings. Track workforce growth and company popularity as alternative data signals. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/linkedin/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) Authenticate using one of the following methods (in order of recommendation): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `META`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | --------------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of data points to return | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.linkedin_data.ticker("META", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/linkedin/META" ``` * Python (requests) ```python import requests url = "https://api.finbrain.tech/v2/linkedin/META" headers = {"Authorization": "Bearer YOUR_API_KEY"} params = {"startDate": "2025-01-01", "endDate": "2026-01-31", "limit": 10} response = requests.get(url, headers=headers, params=params) data = response.json() for entry in data["data"]["data"]: print(f"{entry['date']}: {entry['employeeCount']} employees, " f"{entry['followerCount']} followers, jobs: {entry['jobCount']}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_linkedin_data(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/linkedin/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_linkedin_data("AMZN", "YOUR_API_KEY"); for (auto& entry : result["data"]["data"]) { std::cout << entry["date"].get() << ": " << entry["employeeCount"].get() << " employees, " << entry["followerCount"].get() << " followers" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct LinkedInEntry { date: String, #[serde(rename = "employeeCount")] employee_count: i64, #[serde(rename = "followerCount")] follower_count: i64, #[serde(rename = "jobCount")] job_count: Option, } #[derive(Debug, Deserialize)] struct LinkedInInner { symbol: String, name: String, data: Vec, } #[derive(Debug, Deserialize)] struct LinkedInResponse { success: bool, data: LinkedInInner, } fn get_linkedin_data(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/linkedin/{}", symbol ); let client = Client::new(); let response: LinkedInResponse = client .get(&url) .header("Authorization", format!("Bearer {}", api_key)) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_linkedin_data("AMZN", "YOUR_API_KEY")?; for entry in &result.data.data { println!("{}: {} employees, {} followers, jobs: {:?}", entry.date, entry.employee_count, entry.follower_count, entry.job_count); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/linkedin/META", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const entry of result.data.data) { console.log(`${entry.date}: ${entry.employeeCount} employees, ${entry.followerCount} followers`); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "data": [ { "date": "2026-01-14", "employeeCount": 166090, "followerCount": 18039757, "jobCount": null }, { "date": "2026-01-07", "employeeCount": 165645, "followerCount": 18030998, "jobCount": null } ] }, "meta": { "timestamp": "2026-01-19T15:06:32.503Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | Response data wrapper | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.data` | array | Array of LinkedIn data points | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### LinkedIn Object Fields [Section titled “LinkedIn Object Fields”](#linkedin-object-fields) | Field | Type | Description | | --------------- | ------------ | ----------------------------------------- | | `date` | string | Date (YYYY-MM-DD) | | `employeeCount` | integer | Number of employees on LinkedIn | | `followerCount` | integer | LinkedIn page followers count | | `jobCount` | integer/null | Number of open job postings (may be null) | ## Interpretation [Section titled “Interpretation”](#interpretation) | YoY Growth | Signal | | ---------- | ------------------- | | Above 20% | Rapid expansion | | 10-20% | Healthy growth | | 0-10% | Moderate growth | | -10-0% | Slight contraction | | Below -10% | Significant layoffs | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Symbol not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [LinkedIn Metrics Dataset](/datasets/linkedin-data/) - Use cases and analysis examples * [App Ratings](/api-reference/app-ratings/) - Mobile app metrics * [News Sentiment](/api-reference/sentiment/) - News sentiment # Stock News API > API reference for the FinBrain news endpoint. Retrieve news articles with AI-powered sentiment scores for stock tickers. Retrieve news articles with AI-powered sentiment scores for any stock ticker. Each article includes the headline, source, URL, and an optional sentiment score ranging from -1 (bearish) to 1 (bullish). ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/news/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) Supports multiple authentication methods (in order of preference): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `MSFT`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | --------------------------------------- | | `apiKey` | string | No | Your API key (if not using header auth) | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of articles to return | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("AAPL", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(df) ``` * cURL ```bash # Get news articles curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/news/AAPL" # With date range and limit curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/news/AAPL?startDate=2026-01-01&endDate=2026-01-31&limit=50" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Get news articles response = requests.get( "https://api.finbrain.tech/v2/news/AAPL", headers=headers ) result = response.json() # With date range and limit response = requests.get( "https://api.finbrain.tech/v2/news/AAPL", headers=headers, params={"startDate": "2026-01-01", "endDate": "2026-01-31", "limit": 50} ) result = response.json() ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_news(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/news/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_news("AAPL", "YOUR_API_KEY"); auto data = result["data"]; std::cout << "Symbol: " << data["symbol"].get() << " (" << data["name"].get() << ")" << std::endl; for (auto& article : data["articles"]) { std::cout << article["date"].get() << " | " << article["headline"].get() << " (" << article["source"].get() << ")" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, HeaderValue}; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct ApiResponse { success: bool, data: NewsData, } #[derive(Debug, Deserialize)] struct NewsData { symbol: String, name: String, articles: Vec, } #[derive(Debug, Deserialize)] struct NewsArticle { date: String, headline: String, source: String, url: String, sentiment: Option, } fn get_news(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/news/{}", symbol ); let client = Client::new(); let response: ApiResponse = client .get(&url) .header(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", api_key))?) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_news("AAPL", "YOUR_API_KEY")?; let data = result.data; println!("Symbol: {} ({})", data.symbol, data.name); for article in &data.articles { let sentiment_str = match article.sentiment { Some(s) => format!("{:.3}", s), None => "N/A".to_string(), }; println!("{} | {} ({}) [sentiment: {}]", article.date, article.headline, article.source, sentiment_str); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/news/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); console.log(result.data); ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "articles": [ { "date": "2026-01-19", "headline": "My Forever Portfolio: 5 Stocks I Don't Plan on Ever Selling", "source": "Motley Fool", "url": "https://www.fool.com/investing/2026/01/19/my-forever-portfolio", "sentiment": null }, { "date": "2026-01-19", "headline": "Prediction: These 5 Unstoppable Stocks Could Join the $5 Trillion Club in 2026", "source": "Motley Fool", "url": "https://www.fool.com/investing/2026/01/19/5-trillion-club", "sentiment": 0.1027 }, { "date": "2026-01-19", "headline": "SEC Approves Expanded Option Expirations for Magnificent Seven Stocks", "source": "GuruFocus.com", "url": "https://finance.yahoo.com/news/sec-approves-expanded-option-expirations", "sentiment": 0.765 } ] }, "meta": { "timestamp": "2026-01-19T15:06:22.295Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | --------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | News data container | | `meta` | object | Response metadata | ### Data Object Fields [Section titled “Data Object Fields”](#data-object-fields) | Field | Type | Description | | ---------- | ------ | ----------------------------- | | `symbol` | string | Stock ticker symbol | | `name` | string | Company name | | `articles` | array | Array of news article objects | ### Article Fields [Section titled “Article Fields”](#article-fields) Each item in the `articles` array contains: | Field | Type | Description | | ----------- | -------------- | ---------------------------------------------------------------------------- | | `date` | string | Publication date (YYYY-MM-DD) | | `headline` | string | Article headline | | `source` | string | News source name | | `url` | string | Link to the full article | | `sentiment` | number or null | Sentiment score from -1 (bearish) to 1 (bullish), or `null` if not available | ### Sentiment Score Interpretation [Section titled “Sentiment Score Interpretation”](#sentiment-score-interpretation) | Score Range | Interpretation | | ------------ | ---------------------------------------- | | 0.5 to 1.0 | Strong bullish sentiment | | 0.2 to 0.5 | Moderate bullish sentiment | | -0.2 to 0.2 | Neutral sentiment | | -0.5 to -0.2 | Moderate bearish sentiment | | -1.0 to -0.5 | Strong bearish sentiment | | `null` | Sentiment not available for this article | Known Issue News article URLs may be relative paths instead of full URLs. If a URL starts with `/`, prepend the source’s base URL to construct the full link. ## Usage Examples [Section titled “Usage Examples”](#usage-examples) ### Filter News by Date Range [Section titled “Filter News by Date Range”](#filter-news-by-date-range) ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("AAPL", date_from="2026-01-15", date_to="2026-01-19", as_dataframe=True) for _, article in df.iterrows(): sentiment = article["sentiment"] sentiment_str = f"{sentiment:.3f}" if sentiment is not None else "N/A" print(f"{article['date']} [{sentiment_str}] {article['headline']}") ``` ### Analyze Sentiment Distribution [Section titled “Analyze Sentiment Distribution”](#analyze-sentiment-distribution) ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("TSLA", as_dataframe=True) # Filter articles that have sentiment scores scored = df[df["sentiment"].notna()] if scored.empty: print("No scored articles found") else: avg_sentiment = scored["sentiment"].mean() bullish = (scored["sentiment"] > 0.2).sum() bearish = (scored["sentiment"] < -0.2).sum() neutral = len(scored) - bullish - bearish print(f"TSLA News Sentiment Summary ({len(scored)} scored articles)") print(f" Average sentiment: {avg_sentiment:.3f}") print(f" Bullish articles: {bullish} ({bullish/len(scored)*100:.0f}%)") print(f" Neutral articles: {neutral} ({neutral/len(scored)*100:.0f}%)") print(f" Bearish articles: {bearish} ({bearish/len(scored)*100:.0f}%)") ``` ### Find High-Sentiment Headlines [Section titled “Find High-Sentiment Headlines”](#find-high-sentiment-headlines) ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("NVDA", as_dataframe=True) # Find articles with strong sentiment (positive or negative) scored = df[df["sentiment"].notna()].copy() strong = scored[scored["sentiment"].abs() > 0.5] for _, article in strong.sort_values("sentiment", ascending=False).iterrows(): direction = "Bullish" if article["sentiment"] > 0 else "Bearish" print(f"[{direction} {article['sentiment']:+.3f}] {article['headline']}") print(f" Source: {article['source']} | Date: {article['date']}") ``` ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or query parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [News Sentiment Dataset](/datasets/sentiment/) - Use cases and analysis examples * [News Sentiment API](/api-reference/sentiment/) - Get aggregated sentiment scores * [Price Forecasts](/api-reference/ai-forecasts/) - Get price forecasts # FinBrain API Overview > Complete reference documentation for the FinBrain v2 REST API. Learn about endpoints, authentication, request formats, and response structures. This reference documents all available endpoints in the FinBrain v2 REST API. Use this documentation to integrate FinBrain data into your applications, trading systems, and research workflows. ## Base URL [Section titled “Base URL”](#base-url) All API requests are made to: ```plaintext https://api.finbrain.tech/v2/ ``` ## Authentication [Section titled “Authentication”](#authentication) The v2 API supports four authentication methods. The **Authorization header** is recommended. ### Authorization Header (Recommended) [Section titled “Authorization Header (Recommended)”](#authorization-header-recommended) ```plaintext Authorization: Bearer YOUR_API_KEY ``` ### X-API-Key Header [Section titled “X-API-Key Header”](#x-api-key-header) ```plaintext X-API-Key: YOUR_API_KEY ``` ### Query Parameter [Section titled “Query Parameter”](#query-parameter) ```plaintext ?apiKey=YOUR_API_KEY ``` ### Legacy Query Parameter [Section titled “Legacy Query Parameter”](#legacy-query-parameter) ```plaintext ?token=YOUR_API_KEY ``` See [Authentication](/api-reference/authentication/) for details. ## Available Endpoints [Section titled “Available Endpoints”](#available-endpoints) The FinBrain API delivers 12 alternative datasets plus discovery, screener, and recent-activity endpoints. See the [Datasets Overview](/datasets/overview/) for the conceptual catalog. ### Discovery and Reference [Section titled “Discovery and Reference”](#discovery-and-reference) | Endpoint | Method | Description | | -------------------------------------------------- | ------ | ------------------------------ | | [`/v2/tickers`](/api-reference/available-tickers/) | GET | List available tickers | | [`/v2/markets`](/api-reference/available-markets/) | GET | List available markets | | [`/v2/regions`](/api-reference/regions/) | GET | List markets grouped by region | ### Per-Ticker Endpoints [Section titled “Per-Ticker Endpoints”](#per-ticker-endpoints) #### Government & Regulatory [Section titled “Government & Regulatory”](#government--regulatory) | Endpoint | Method | Description | | --------------------------------------------------------------------------- | ------ | ---------------------------------------------- | | [`/v2/congress/house/{symbol}`](/api-reference/congressional-trading/) | GET | US House member trades from STOCK Act filings | | [`/v2/congress/senate/{symbol}`](/api-reference/congressional-trading/) | GET | US Senate member trades from STOCK Act filings | | [`/v2/lobbying/{symbol}`](/api-reference/corporate-lobbying/) | GET | Federal lobbying disclosure filings | | [`/v2/government-contracts/{symbol}`](/api-reference/government-contracts/) | GET | Federal contract awards | | [`/v2/patent-filings/{symbol}`](/api-reference/patent-filings/) | GET | USPTO granted patents | #### Social & Consumer Intelligence [Section titled “Social & Consumer Intelligence”](#social--consumer-intelligence) | Endpoint | Method | Description | | ----------------------------------------------------------------- | ------ | ------------------------------------------- | | [`/v2/sentiment/{symbol}`](/api-reference/sentiment/) | GET | AI-generated news sentiment scores | | [`/v2/news/{symbol}`](/api-reference/news/) | GET | Recent news articles with sentiment | | [`/v2/linkedin/{symbol}`](/api-reference/linkedin-data/) | GET | LinkedIn employee and follower metrics | | [`/v2/app-ratings/{symbol}`](/api-reference/app-ratings/) | GET | iOS and Android app ratings | | [`/v2/reddit-mentions/{symbol}`](/api-reference/reddit-mentions/) | GET | Reddit mentions across investing subreddits | #### Market & Trading Signals [Section titled “Market & Trading Signals”](#market--trading-signals) | Endpoint | Method | Description | | ---------------------------------------------------------------------- | ------ | ----------------------------------------- | | [`/v2/predictions/{type}/{symbol}`](/api-reference/ai-forecasts/) | GET | Price forecasts with confidence intervals | | [`/v2/analyst-ratings/{symbol}`](/api-reference/analyst-ratings/) | GET | Wall Street ratings and price targets | | [`/v2/put-call-ratio/{symbol}`](/api-reference/put-call/) | GET | Options put/call ratios and flow | | [`/v2/insider-trading/{symbol}`](/api-reference/insider-transactions/) | GET | SEC Form 4 insider transactions | ### Screeners (Cross-Ticker) [Section titled “Screeners (Cross-Ticker)”](#screeners-cross-ticker) Screen any dataset across all available tickers. See [Stock Screener](/api-reference/screener/) for full reference. | Endpoint | Description | | ----------------------------------- | --------------------------------- | | `/v2/screener/predictions/daily` | Screen daily price forecasts | | `/v2/screener/predictions/monthly` | Screen monthly price forecasts | | `/v2/screener/sentiment` | Screen news sentiment scores | | `/v2/screener/news` | Screen news articles | | `/v2/screener/analyst-ratings` | Screen analyst ratings | | `/v2/screener/put-call-ratio` | Screen put/call ratios | | `/v2/screener/insider-trading` | Screen insider trades | | `/v2/screener/congress/house` | Screen House member trades | | `/v2/screener/congress/senate` | Screen Senate member trades | | `/v2/screener/lobbying` | Screen corporate lobbying filings | | `/v2/screener/government-contracts` | Screen government contract awards | | `/v2/screener/patent-filings` | Screen patent filings | | `/v2/screener/linkedin` | Screen LinkedIn metrics | | `/v2/screener/app-ratings` | Screen app ratings | | `/v2/screener/reddit-mentions` | Screen Reddit mentions | ### Recent Activity [Section titled “Recent Activity”](#recent-activity) Retrieve the most recent entries across all tickers without specifying a symbol. See [Recent Activity](/api-reference/recent/) for full reference. | Endpoint | Description | | ---------------------------- | --------------------------- | | `/v2/recent/news` | Most recent news articles | | `/v2/recent/analyst-ratings` | Most recent analyst ratings | ## Request Format [Section titled “Request Format”](#request-format) ### URL Parameters [Section titled “URL Parameters”](#url-parameters) | Parameter | Description | Example | | ---------- | --------------------- | ------------------------- | | `{symbol}` | Stock or asset symbol | `AAPL`, `TSLA`, `BTC-USD` | | `{type}` | Prediction type | `daily`, `monthly` | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Required | Description | | ----------- | ------------------------------ | -------------------------------------------- | | `apiKey` | Yes (if not using header auth) | Your API key | | `startDate` | No | Start date (YYYY-MM-DD) | | `endDate` | No | End date (YYYY-MM-DD) | | `limit` | No | Maximum number of results to return | | `market` | No | Filter by market (e.g., `NASDAQ`, `S&P 500`) | | `region` | No | Filter by region (e.g., `US`, `Global`) | ### Example Request [Section titled “Example Request”](#example-request) * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" ``` * Python ```python import requests url = "https://api.finbrain.tech/v2/predictions/daily/AAPL" headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get(url, headers=headers) data = response.json() ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/predictions/daily/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const data = await response.json(); ``` ## Response Format [Section titled “Response Format”](#response-format) All responses are returned as JSON using a standardized envelope. ### Success Response [Section titled “Success Response”](#success-response) ```json { "success": true, "data": { // ... endpoint-specific data }, "meta": { "timestamp": "2026-01-17T12:00:00.000Z" } } ``` ### Error Response [Section titled “Error Response”](#error-response) ```json { "success": false, "error": { "code": "ERROR_CODE", "message": "Human-readable message" } } ``` ## HTTP Status Codes [Section titled “HTTP Status Codes”](#http-status-codes) | Code | Meaning | | ---- | --------------------------------------- | | 200 | Success | | 400 | Bad Request - Invalid parameters | | 401 | Unauthorized - Invalid API key | | 403 | Forbidden - Access denied | | 404 | Not Found - Data not found | | 429 | Too Many Requests - Rate limit exceeded | | 500 | Internal Server Error | See [Error Codes](/api-reference/errors/) for detailed error documentation. ## Rate Limiting [Section titled “Rate Limiting”](#rate-limiting) Rate limits are enforced per API key. The following headers are included in every response: | Header | Description | | ----------------------- | ------------------------------------------------ | | `X-RateLimit-Limit` | Maximum requests allowed in the current window | | `X-RateLimit-Remaining` | Requests remaining in the current window | | `X-RateLimit-Reset` | Unix timestamp when the rate limit window resets | ### Rate Limit Tiers [Section titled “Rate Limit Tiers”](#rate-limit-tiers) | Plan | Rate Limit | | ---------- | --------------------------------------------------------------- | | Enterprise | Sized to your throughput requirements, negotiated per agreement | **API access is part of an Enterprise agreement.** The self-serve Professional plan is the FinBrain Terminal browser platform and does not include programmatic access. To evaluate the API, [get in touch](/enterprise/) — institutional evaluations run on a scoped 30-day trial key with live data and a trailing 24 months of history. When you exceed the rate limit, the API returns a `429 Too Many Requests` status. Wait until the time indicated by `X-RateLimit-Reset` before retrying. ## SDKs and Libraries [Section titled “SDKs and Libraries”](#sdks-and-libraries) For easier integration, use our official SDK: * [Python SDK](/integrations/python/) - `pip install finbrain-python` * [MCP Integration](/integrations/mcp/) - `pip install finbrain-mcp` ## Next Steps [Section titled “Next Steps”](#next-steps) * [Authentication](/api-reference/authentication/) - Learn about API authentication * [Available Markets](/api-reference/available-markets/) - Discover available markets * [Price Forecasts](/api-reference/ai-forecasts/) - Get price forecasts * [Error Codes](/api-reference/errors/) - Handle errors properly # Patent Filings API > API reference for the FinBrain patent filings endpoint. Retrieve USPTO granted patents with technology classifications, claim counts, and inventors mapped to stock tickers. Retrieve USPTO granted patents mapped to stock tickers. Track patent grants, technology classifications (CPC), claim counts, inventors, and filing-to-grant timing for any covered company. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/patent-filings/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) The API supports multiple authentication methods: | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `NVDA`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ------------------------------------------- | | `startDate` | string | No | Start date for grant date (YYYY-MM-DD) | | `endDate` | string | No | End date for grant date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return (1-500) | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.patent_filings.ticker("AAPL", date_from="2025-01-01", date_to="2025-12-31", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/patent-filings/AAPL", headers=headers, params={"limit": 10} ) data = response.json() for p in data["data"]["patents"]: print(f"{p['patentDate']} {p['patentId']} " f"[{p['primaryCpcSection']}] {p['title']}") ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/patent-filings/AAPL" ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_patent_filings(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/patent-filings/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_patent_filings("AAPL", "YOUR_API_KEY"); for (auto& p : result["data"]["patents"]) { std::cout << p["patentDate"].get() << " " << p["patentId"].get() << " [" << p["primaryCpcSection"].get() << "] " << p["title"].get() << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct Patent { #[serde(rename = "patentId")] patent_id: String, #[serde(rename = "patentDate")] patent_date: String, title: String, #[serde(rename = "type")] patent_type: String, kind: String, #[serde(rename = "numClaims")] num_claims: i64, #[serde(rename = "numCitedBy")] num_cited_by: i64, #[serde(rename = "assigneeOrganization")] assignee_organization: String, #[serde(rename = "assigneeType")] assignee_type: String, #[serde(rename = "applicationFilingDate")] application_filing_date: String, #[serde(rename = "filingToGrantDays")] filing_to_grant_days: i64, inventors: Vec, #[serde(rename = "numInventors")] num_inventors: i64, #[serde(rename = "cpcSections")] cpc_sections: Vec, #[serde(rename = "cpcSubsections")] cpc_subsections: Vec, #[serde(rename = "primaryCpcSection")] primary_cpc_section: String, } #[derive(Debug, Deserialize)] struct PatentData { symbol: String, name: String, patents: Vec, } #[derive(Debug, Deserialize)] struct PatentResponse { success: bool, data: PatentData, } fn get_patent_filings(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/patent-filings/{}", symbol ); let client = Client::new(); let response: PatentResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_patent_filings("AAPL", "YOUR_API_KEY")?; for p in &result.data.patents { println!("{} {} [{}] {}", p.patent_date, p.patent_id, p.primary_cpc_section, p.title); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/patent-filings/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const p of result.data.patents) { console.log(`${p.patentDate} ${p.patentId} [${p.primaryCpcSection}] ${p.title}`); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "patents": [ { "patentId": "12345678", "patentDate": "2025-03-11", "title": "Method and apparatus for low-power display synchronization", "type": "utility", "kind": "B2", "numClaims": 20, "numCitedBy": 0, "assigneeOrganization": "Apple Inc.", "assigneeType": "2", "applicationFilingDate": "2022-06-15", "filingToGrantDays": 999, "inventors": ["John Doe", "Jane Smith"], "numInventors": 2, "cpcSections": ["G", "H"], "cpcSubsections": ["G06", "H04"], "primaryCpcSection": "G", "cik": "0000320193" } ] }, "meta": { "timestamp": "2026-06-16T12:00:00.000Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.patents` | array | Array of granted patent objects | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Patent Object Fields [Section titled “Patent Object Fields”](#patent-object-fields) | Field | Type | Description | | ----------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `patentId` | string | USPTO patent number (globally unique) | | `patentDate` | string | Grant date (YYYY-MM-DD) | | `title` | string | Patent title | | `type` | string | Patent type (utility, design, plant, reissue) | | `kind` | string | USPTO kind code (e.g., `B2`, `S1`) | | `numClaims` | number | Number of claims in the patent | | `numCitedBy` | number | Forward-citation count | | `assigneeOrganization` | string | Organization the patent is assigned to | | `assigneeType` | string | Assignee type code (`2` = US company, `3` = foreign company) | | `applicationFilingDate` | string | Original application filing date (YYYY-MM-DD) | | `filingToGrantDays` | number | Days from filing to grant | | `inventors` | array | Named inventors | | `numInventors` | number | Number of inventors | | `cpcSections` | array | CPC classification sections | | `cpcSubsections` | array | CPC subsections | | `primaryCpcSection` | string | Leading CPC section | | `cik` | string \| null | SEC Central Index Key of the company as of this record — 10-digit zero-padded string, `null` when unresolved. Delivered for joining to your own SEC-keyed data; the API cannot be queried by CIK | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Patent Filings Dataset](/datasets/patent-filings/) - Use cases and analysis examples * [Stock Screener API](/api-reference/screener/) - Screen patent filings across tickers * [Government Contracts API](/api-reference/government-contracts/) - Federal contract awards * [Insider Transactions API](/api-reference/insider-transactions/) - Insider trading data # Put/Call Data API > API reference for the FinBrain put/call data endpoint. Retrieve options market put/call ratios and volume data. Retrieve options market data including put/call ratios, volume, and price. Track options positioning and sentiment. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/put-call-ratio/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) Authenticate using one of the following methods (in order of recommendation): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `MSFT`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ----------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.options.put_call("AAPL", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/put-call-ratio/AAPL" ``` * Python (requests) ```python import requests url = "https://api.finbrain.tech/v2/put-call-ratio/AAPL" headers = {"Authorization": "Bearer YOUR_API_KEY"} params = {"startDate": "2026-01-01", "endDate": "2026-01-31"} response = requests.get(url, headers=headers, params=params) data = response.json() for pc in data["data"]["data"]: print(f"{pc['date']}: ratio {pc['ratio']:.2f} " f"(calls: {pc['callVolume']}, puts: {pc['putVolume']}, " f"total: {pc['totalVolume']}, price: {pc['price']})") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_put_call_data(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/put-call-ratio/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_put_call_data("AAPL", "YOUR_API_KEY"); for (auto& pc : result["data"]["data"]) { std::cout << pc["date"].get() << ": ratio " << pc["ratio"].get() << " (calls: " << pc["callVolume"].get() << ", puts: " << pc["putVolume"].get() << ", total: " << pc["totalVolume"].get() << ", price: " << pc["price"].get() << ")" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct PutCallEntry { date: String, ratio: f64, #[serde(rename = "callVolume")] call_volume: i64, #[serde(rename = "putVolume")] put_volume: i64, #[serde(rename = "totalVolume")] total_volume: i64, price: f64, } #[derive(Debug, Deserialize)] struct PutCallData { symbol: String, name: String, data: Vec, } #[derive(Debug, Deserialize)] struct Meta { timestamp: String, } #[derive(Debug, Deserialize)] struct PutCallResponse { success: bool, data: PutCallData, meta: Meta, } fn get_put_call_data(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/put-call-ratio/{}", symbol ); let client = Client::new(); let response: PutCallResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_put_call_data("AAPL", "YOUR_API_KEY")?; for pc in &result.data.data { println!("{}: ratio {:.2} (calls: {}, puts: {}, total: {}, price: {:.2})", pc.date, pc.ratio, pc.call_volume, pc.put_volume, pc.total_volume, pc.price); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/put-call-ratio/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const { data } = await response.json(); data.data.forEach(pc => { console.log(`${pc.date}: ratio ${pc.ratio} (calls: ${pc.callVolume}, puts: ${pc.putVolume}, total: ${pc.totalVolume}, price: ${pc.price})`); }); ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "data": [ { "date": "2026-01-19", "ratio": 0.5, "callVolume": 620689, "putVolume": 310344, "totalVolume": 931034, "price": 255.53 }, { "date": "2026-01-16", "ratio": 1.42, "callVolume": 442233, "putVolume": 627971, "totalVolume": 1070205, "price": 258.21 } ] }, "meta": { "timestamp": "2026-01-19T15:06:21.343Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ----------------------------- | | `success` | boolean | Whether the request succeeded | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.data` | array | Array of put/call data points | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Put/Call Object Fields [Section titled “Put/Call Object Fields”](#putcall-object-fields) | Field | Type | Description | | ------------- | ------- | ----------------------------------- | | `date` | string | Date (YYYY-MM-DD) | | `ratio` | number | Put/call ratio | | `callVolume` | integer | Call options volume | | `putVolume` | integer | Put options volume | | `totalVolume` | integer | Total options volume (calls + puts) | | `price` | number | Closing price on this date | ## Interpretation [Section titled “Interpretation”](#interpretation) | Ratio | Interpretation | | --------- | ------------------------------------ | | Above 1.2 | Heavy put activity (bearish/hedging) | | 0.7 - 1.2 | Normal range | | Below 0.7 | Heavy call activity (bullish) | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Symbol not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Put/Call Ratio Dataset](/datasets/put-call/) - Use cases and analysis examples * [News Sentiment](/api-reference/sentiment/) - News sentiment * [Analyst Ratings](/api-reference/analyst-ratings/) - Wall Street ratings * [Price Forecasts](/api-reference/ai-forecasts/) - Price forecasts # Recent Activity API > API reference for the FinBrain recent data endpoints. Get the most recent news articles and analyst ratings across all tracked tickers. Recent endpoints return the latest data entries sorted by date across all tracked stocks. Use these endpoints to stay on top of breaking news and fresh analyst actions without querying tickers individually. ## Authentication [Section titled “Authentication”](#authentication) Supports multiple authentication methods (in order of preference): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Endpoints [Section titled “Endpoints”](#endpoints) | Endpoint | Description | | -------------------------------- | --------------------------- | | `GET /v2/recent/news` | Most recent news articles | | `GET /v2/recent/analyst-ratings` | Most recent analyst ratings | ## Common Query Parameters [Section titled “Common Query Parameters”](#common-query-parameters) | Parameter | Type | Required | Description | | --------- | ------- | -------- | --------------------------------------------------- | | `apiKey` | string | No | Your API key (if not using header auth) | | `limit` | integer | No | Number of results to return (1-20,000, default 100) | | `market` | string | No | Filter by market name (e.g., `NASDAQ`, `S&P 500`) | | `region` | string | No | Filter by region code (e.g., `US`, `UK`) | ## Request [Section titled “Request”](#request) ### Recent News [Section titled “Recent News”](#recent-news) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Recent news df = fb.recent.news(limit=20, as_dataframe=True) print(df) # Recent analyst ratings df = fb.recent.analyst_ratings(limit=10, as_dataframe=True) print(df) ``` * cURL ```bash # Get 100 most recent news articles (default) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/recent/news" # Filter by market with custom limit curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/recent/news?market=NASDAQ&limit=50" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Get 100 most recent news articles (default) response = requests.get( "https://api.finbrain.tech/v2/recent/news", headers=headers ) result = response.json() for article in result["data"]["data"]: print(f"{article['symbol']} - {article['headline']} " f"(sentiment: {article['sentiment']:.3f})") # Filter by market response = requests.get( "https://api.finbrain.tech/v2/recent/news", headers=headers, params={"market": "NASDAQ", "limit": 50} ) result = response.json() print(f"Total articles: {result['data']['summary']['totalArticles']}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_recent_news(int limit, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/recent/news?limit=" + std::to_string(limit); struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_recent_news(100, "YOUR_API_KEY"); for (auto& article : result["data"]["data"]) { std::cout << article["symbol"].get() << " - " << article["headline"].get() << " (" << article["sentiment"].get() << ")" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct RecentNewsResponse { success: bool, data: RecentNewsData, } #[derive(Debug, Deserialize)] struct RecentNewsData { data: Vec, summary: NewsSummary, } #[derive(Debug, Deserialize)] struct NewsEntry { symbol: String, name: String, date: String, headline: String, source: String, url: String, sentiment: f64, } #[derive(Debug, Deserialize)] struct NewsSummary { #[serde(rename = "totalArticles")] total_articles: i64, #[serde(rename = "totalTickers")] total_tickers: i64, #[serde(rename = "averageSentiment")] average_sentiment: f64, } fn get_recent_news(limit: i32, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/recent/news?limit={}", limit ); let client = Client::new(); let response: RecentNewsResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_recent_news(100, "YOUR_API_KEY")?; for article in &result.data.data { println!("{} - {} (sentiment: {:.3})", article.symbol, article.headline, article.sentiment); } println!("Total articles: {}", result.data.summary.total_articles); Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/recent/news?limit=100", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const article of result.data.data) { console.log(`${article.symbol} - ${article.headline} (sentiment: ${article.sentiment})`); } console.log(`Total articles: ${result.data.summary.totalArticles}`); ``` ### Recent Analyst Ratings [Section titled “Recent Analyst Ratings”](#recent-analyst-ratings) * cURL ```bash # Get 100 most recent analyst ratings (default) curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/recent/analyst-ratings" # Filter by region curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/recent/analyst-ratings?region=US&limit=200" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/recent/analyst-ratings", headers=headers, params={"limit": 200} ) result = response.json() for rating in result["data"]["data"]: print(f"{rating['symbol']} - {rating['institution']}: " f"{rating['action']} ({rating['rating']}) " f"Target: {rating['targetPrice']}") summary = result["data"]["summary"] print(f"\nUpgrades: {summary['upgradeCount']}, " f"Downgrades: {summary['downgradeCount']}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_recent_analyst_ratings(int limit, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/recent/analyst-ratings?limit=" + std::to_string(limit); struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_recent_analyst_ratings(200, "YOUR_API_KEY"); for (auto& rating : result["data"]["data"]) { std::cout << rating["symbol"].get() << " - " << rating["institution"].get() << ": " << rating["action"].get() << " (" << rating["rating"].get() << ") " << "Target: " << rating["targetPrice"].get() << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct AnalystRatingsResponse { success: bool, data: AnalystRatingsData, } #[derive(Debug, Deserialize)] struct AnalystRatingsData { data: Vec, summary: RatingsSummary, } #[derive(Debug, Deserialize)] struct RatingEntry { symbol: String, name: String, date: String, institution: String, action: String, rating: String, #[serde(rename = "targetPrice")] target_price: String, } #[derive(Debug, Deserialize)] struct RatingsSummary { #[serde(rename = "totalRatings")] total_ratings: i64, #[serde(rename = "totalTickers")] total_tickers: i64, #[serde(rename = "upgradeCount")] upgrade_count: i64, #[serde(rename = "downgradeCount")] downgrade_count: i64, } fn get_recent_analyst_ratings(limit: i32, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/recent/analyst-ratings?limit={}", limit ); let client = Client::new(); let response: AnalystRatingsResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_recent_analyst_ratings(200, "YOUR_API_KEY")?; for rating in &result.data.data { println!("{} - {}: {} ({}) Target: {}", rating.symbol, rating.institution, rating.action, rating.rating, rating.target_price); } println!("Upgrades: {}, Downgrades: {}", result.data.summary.upgrade_count, result.data.summary.downgrade_count); Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/recent/analyst-ratings?limit=200", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const rating of result.data.data) { console.log(`${rating.symbol} - ${rating.institution}: ${rating.action} (${rating.rating}) Target: ${rating.targetPrice}`); } const { upgradeCount, downgradeCount } = result.data.summary; console.log(`Upgrades: ${upgradeCount}, Downgrades: ${downgradeCount}`); ``` ## Responses [Section titled “Responses”](#responses) ### Recent News Response (200 OK) [Section titled “Recent News Response (200 OK)”](#recent-news-response-200-ok) ```json { "success": true, "data": { "data": [ { "symbol": "VRT", "name": "Vertiv Holdings Co", "date": "2026-01-19", "headline": "Amazon, Carvana And Others: Bank Of America Reveals 5 Stocks", "source": "Benzinga", "url": "https://www.benzinga.com/news/280015", "sentiment": 0.6705 } ], "summary": { "totalArticles": 100, "totalTickers": 87, "averageSentiment": 0.42 } }, "meta": { "timestamp": "2026-01-19T15:23:13.813Z" } } ``` ### News Entry Fields [Section titled “News Entry Fields”](#news-entry-fields) | Field | Type | Description | | ----------- | ------ | ------------------------------------------------ | | `symbol` | string | Stock ticker symbol | | `name` | string | Company name | | `date` | string | Article date (YYYY-MM-DD) | | `headline` | string | News article headline | | `source` | string | News source (e.g., Benzinga, Reuters) | | `url` | string | Link to the original article | | `sentiment` | number | Sentiment score from -1 (bearish) to 1 (bullish) | ### News Summary Fields [Section titled “News Summary Fields”](#news-summary-fields) | Field | Type | Description | | ------------------ | ------- | ------------------------------------- | | `totalArticles` | integer | Total number of articles returned | | `totalTickers` | integer | Number of unique tickers mentioned | | `averageSentiment` | number | Average sentiment across all articles | ### Recent Analyst Ratings Response (200 OK) [Section titled “Recent Analyst Ratings Response (200 OK)”](#recent-analyst-ratings-response-200-ok) ```json { "success": true, "data": { "data": [ { "symbol": "AFYA", "name": "Afya Ltd", "date": "2026-01-16", "institution": "UBS", "action": "Downgrade", "rating": "Buy → Neutral", "targetPrice": "$16" } ], "summary": { "totalRatings": 100, "totalTickers": 95, "upgradeCount": 18, "downgradeCount": 12 } }, "meta": { "timestamp": "2026-01-19T15:23:11.771Z" } } ``` ### Analyst Rating Entry Fields [Section titled “Analyst Rating Entry Fields”](#analyst-rating-entry-fields) | Field | Type | Description | | ------------- | ------ | ------------------------------------------------------------- | | `symbol` | string | Stock ticker symbol | | `name` | string | Company name | | `date` | string | Rating date (YYYY-MM-DD) | | `institution` | string | Analyst firm (e.g., UBS, Goldman Sachs) | | `action` | string | Rating action (e.g., Upgrade, Downgrade, Initiate, Reiterate) | | `rating` | string | Rating change (e.g., “Buy to Neutral”) | | `targetPrice` | string | Price target set by the analyst | ### Analyst Ratings Summary Fields [Section titled “Analyst Ratings Summary Fields”](#analyst-ratings-summary-fields) | Field | Type | Description | | ---------------- | ------- | ------------------------------------- | | `totalRatings` | integer | Total number of ratings returned | | `totalTickers` | integer | Number of unique tickers with ratings | | `upgradeCount` | integer | Number of upgrades | | `downgradeCount` | integer | Number of downgrades | ## Usage Examples [Section titled “Usage Examples”](#usage-examples) ### News Sentiment Monitor [Section titled “News Sentiment Monitor”](#news-sentiment-monitor) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/recent/news", headers=headers, params={"limit": 500} ) result = response.json() # Group articles by ticker from collections import defaultdict by_ticker = defaultdict(list) for article in result["data"]["data"]: by_ticker[article["symbol"]].append(article) # Find tickers with the most news activity print("Most mentioned tickers:") for symbol, articles in sorted(by_ticker.items(), key=lambda x: -len(x[1]))[:10]: avg_sentiment = sum(a["sentiment"] for a in articles) / len(articles) print(f" {symbol:>6}: {len(articles)} articles, avg sentiment {avg_sentiment:.3f}") ``` ### Track Analyst Upgrades and Downgrades [Section titled “Track Analyst Upgrades and Downgrades”](#track-analyst-upgrades-and-downgrades) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/recent/analyst-ratings", headers=headers, params={"limit": 500} ) result = response.json() upgrades = [r for r in result["data"]["data"] if r["action"] == "Upgrade"] downgrades = [r for r in result["data"]["data"] if r["action"] == "Downgrade"] print(f"Recent Upgrades ({len(upgrades)}):") for r in upgrades[:5]: print(f" {r['symbol']:>6} - {r['institution']}: {r['rating']} (Target: {r['targetPrice']})") print(f"\nRecent Downgrades ({len(downgrades)}):") for r in downgrades[:5]: print(f" {r['symbol']:>6} - {r['institution']}: {r['rating']} (Target: {r['targetPrice']})") ``` ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Endpoint not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [News Sentiment API](/api-reference/sentiment/) - Get sentiment for a single ticker * [Analyst Ratings API](/api-reference/analyst-ratings/) - Get analyst ratings for a single ticker * [Screener API](/api-reference/screener/) - Screen and filter across multiple tickers * [News Sentiment Dataset](/datasets/sentiment/) - Use cases and analysis examples * [Analyst Ratings Dataset](/datasets/analyst-ratings/) - Use cases and analysis examples # Reddit Mentions API > API reference for the FinBrain Reddit mentions endpoint. Retrieve ticker mention counts across Reddit investing communities including WallStreetBets, r/stocks, and more. Retrieve ticker mention counts across Reddit investing communities. Track how often a stock is discussed on WallStreetBets, r/stocks, and other subreddits with data collected every 4 hours. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/reddit-mentions/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) The API supports multiple authentication methods: | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------------------------------------- | | `symbol` | string | Yes | Stock ticker symbol (e.g., `TSLA`, `GME`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ------------------------------------------- | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return (1-500) | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.reddit_mentions.ticker("TSLA", date_from="2026-03-01", date_to="2026-03-16", as_dataframe=True) print(df) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/reddit-mentions/TSLA" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/reddit-mentions/TSLA", headers=headers, params={"limit": 10} ) data = response.json() for d in data["data"]["data"]: print(f"{d['date']} r/{d['subreddit']}: {d['mentions']} mentions") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_reddit_mentions(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/reddit-mentions/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_reddit_mentions("TSLA", "YOUR_API_KEY"); for (auto& d : result["data"]["data"]) { std::cout << d["date"].get() << " r/" << d["subreddit"].get() << ": " << d["mentions"].get() << " mentions" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct RedditMention { date: String, subreddit: String, mentions: i64, } #[derive(Debug, Deserialize)] struct RedditMentionsData { symbol: String, name: String, data: Vec, } #[derive(Debug, Deserialize)] struct RedditMentionsResponse { success: bool, data: RedditMentionsData, } fn get_reddit_mentions(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/reddit-mentions/{}", symbol ); let client = Client::new(); let response: RedditMentionsResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_reddit_mentions("TSLA", "YOUR_API_KEY")?; for d in &result.data.data { println!("{} r/{}: {} mentions", d.date, d.subreddit, d.mentions); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/reddit-mentions/TSLA", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const d of result.data.data) { console.log(`${d.date} r/${d.subreddit}: ${d.mentions} mentions`); } ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "TSLA", "name": "Tesla, Inc.", "data": [ { "date": "2026-03-16T14:00:00.000Z", "subreddit": "_all", "mentions": 57 }, { "date": "2026-03-16T14:00:00.000Z", "subreddit": "wallstreetbets", "mentions": 45 }, { "date": "2026-03-16T14:00:00.000Z", "subreddit": "stocks", "mentions": 12 } ] }, "meta": { "timestamp": "2026-03-17T15:05:59.853Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | ---------------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data.symbol` | string | Stock ticker symbol | | `data.name` | string | Company name | | `data.data` | array | Array of mention count objects | | `meta.timestamp` | string | Response timestamp (ISO 8601) | ### Data Object Fields [Section titled “Data Object Fields”](#data-object-fields) | Field | Type | Description | | ----------- | ------- | ------------------------------------------------------------------- | | `date` | string | Snapshot timestamp (ISO 8601) | | `subreddit` | string | Subreddit name, or `_all` for aggregate total across all subreddits | | `mentions` | integer | Number of ticker mentions in this snapshot | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol or parameters | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Reddit Mentions Dataset](/datasets/reddit-mentions/) - Use cases and analysis examples * [Stock Screener API](/api-reference/screener/) - Screen Reddit mentions across tickers * [Stock Sentiment API](/api-reference/sentiment/) - News sentiment scores * [Stock News API](/api-reference/news/) - News articles with sentiment # Available Regions API > API reference for the FinBrain regions endpoint. List all available markets grouped by geographic region. List all available markets grouped by geographic region. Use this discovery endpoint to find which markets are available in each region before querying for tickers or predictions. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/regions ``` ## Authentication [Section titled “Authentication”](#authentication) Supports multiple authentication methods (in order of preference): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | --------------------------------------- | | `apiKey` | string | No | Your API key (if not using header auth) | This endpoint has no path parameters or additional query parameters. ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") regions = fb.available.regions(as_dataframe=True) print(regions) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/regions" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/regions", headers=headers ) result = response.json() ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_regions(const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/regions"; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_regions("YOUR_API_KEY"); for (auto& region : result["data"]["regions"]) { std::cout << region["region"].get() << ":" << std::endl; for (auto& market : region["markets"]) { std::cout << " - " << market.get() << std::endl; } } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, HeaderValue}; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct ApiResponse { success: bool, data: RegionsData, } #[derive(Debug, Deserialize)] struct RegionsData { regions: Vec, } #[derive(Debug, Deserialize)] struct Region { region: String, markets: Vec, } fn get_regions(api_key: &str) -> Result> { let client = Client::new(); let response: ApiResponse = client .get("https://api.finbrain.tech/v2/regions") .header(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", api_key))?) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_regions("YOUR_API_KEY")?; for region in &result.data.regions { println!("{}:", region.region); for market in ®ion.markets { println!(" - {}", market); } } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/regions", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); console.log(result.data); ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "regions": [ { "region": "US", "markets": ["DOW 30", "NASDAQ", "NYSE", "S&P 500"] }, { "region": "UK", "markets": ["UK FTSE 100"] }, { "region": "DE", "markets": ["Germany DAX"] }, { "region": "Global", "markets": ["Commodities", "Crypto Currencies", "ETFs", "Foreign Exchange", "Index Futures"] } ] }, "meta": { "timestamp": "2026-01-19T15:05:55.187Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | --------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | Regions data container | | `meta` | object | Response metadata | ### Data Object Fields [Section titled “Data Object Fields”](#data-object-fields) | Field | Type | Description | | --------- | ----- | ----------------------- | | `regions` | array | Array of region objects | ### Region Fields [Section titled “Region Fields”](#region-fields) Each item in the `regions` array contains: | Field | Type | Description | | --------- | ------ | ----------------------------------------------------- | | `region` | string | Region code (e.g., `US`, `UK`, `DE`, `Global`) | | `markets` | array | Array of market name strings available in this region | ## Usage Examples [Section titled “Usage Examples”](#usage-examples) ### List All Markets in a Region [Section titled “List All Markets in a Region”](#list-all-markets-in-a-region) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/regions", headers=headers ) result = response.json() regions = result["data"]["regions"] # Find all US markets for region in regions: if region["region"] == "US": print("US Markets:") for market in region["markets"]: print(f" - {market}") ``` ### Build a Region-to-Markets Lookup [Section titled “Build a Region-to-Markets Lookup”](#build-a-region-to-markets-lookup) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/regions", headers=headers ) result = response.json() regions = result["data"]["regions"] # Create a lookup dictionary region_map = {r["region"]: r["markets"] for r in regions} # Use it for filtering print(f"Global markets: {', '.join(region_map.get('Global', []))}") print(f"Total regions: {len(region_map)}") print(f"Total markets: {sum(len(m) for m in region_map.values())}") ``` ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | -------------------------- | | 401 | Unauthorized | Invalid or missing API key | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [Available Markets](/api-reference/available-markets/) - List markets (v1 endpoint) * [Available Tickers](/api-reference/available-tickers/) - Get tickers for a market * [Market Predictions](/api-reference/market-predictions/) - Get predictions for a market # Stock Screener API > API reference for the FinBrain screener endpoints. Screen and filter data across multiple tickers in a single request by market or region. Screener endpoints let you fetch data across multiple tickers in a single request. Filter by market or region to narrow results. Instead of querying tickers one by one, use the screener to scan entire markets for sentiment shifts, insider trades, congressional activity, and more. ## Authentication [Section titled “Authentication”](#authentication) Supports multiple authentication methods (in order of preference): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Endpoints [Section titled “Endpoints”](#endpoints) | Endpoint | Description | Requires market/region? | | --------------------------------------- | --------------------------------- | ----------------------- | | `GET /v2/screener/sentiment` | Screen sentiment across tickers | Yes (market OR region) | | `GET /v2/screener/analyst-ratings` | Screen analyst ratings | No (optional) | | `GET /v2/screener/insider-trading` | Screen insider trades | No | | `GET /v2/screener/congress/house` | Screen House trades | No | | `GET /v2/screener/congress/senate` | Screen Senate trades | No | | `GET /v2/screener/news` | Screen news articles | No (optional) | | `GET /v2/screener/put-call-ratio` | Screen put/call ratios | No (optional) | | `GET /v2/screener/linkedin` | Screen LinkedIn data | Yes (market OR region) | | `GET /v2/screener/app-ratings` | Screen app ratings | Yes (market OR region) | | `GET /v2/screener/lobbying` | Screen corporate lobbying filings | No | | `GET /v2/screener/government-contracts` | Screen government contract awards | No | | `GET /v2/screener/reddit-mentions` | Screen Reddit mentions | No (optional) | | `GET /v2/screener/predictions/daily` | Screen daily predictions | No (optional) | | `GET /v2/screener/predictions/monthly` | Screen monthly predictions | No (optional) | Note Endpoints marked “Yes” for market/region **require** at least one of `market` or `region` as a query parameter. All other endpoints accept them as optional filters. ## Common Query Parameters [Section titled “Common Query Parameters”](#common-query-parameters) | Parameter | Type | Required | Description | | --------- | ------- | -------- | ------------------------------------------------- | | `apiKey` | string | No | Your API key (if not using header auth) | | `limit` | integer | No | Number of results to return (1-20,000) | | `market` | string | No | Filter by market name (e.g., `NASDAQ`, `S&P 500`) | | `region` | string | No | Filter by region code (e.g., `US`, `UK`) | ## Request Examples [Section titled “Request Examples”](#request-examples) ### Sentiment Screener [Section titled “Sentiment Screener”](#sentiment-screener) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Screen predictions by market df = fb.screener.predictions_daily(market="S&P 500", as_dataframe=True) print(df) # Screen insider trading (no market filter needed) df = fb.screener.insider_trading(as_dataframe=True) print(df) ``` * cURL ```bash # Screen sentiment for a specific market curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/screener/sentiment?market=NASDAQ&limit=10" # Screen sentiment by region curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/screener/sentiment?region=US&limit=50" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Screen sentiment for a specific market response = requests.get( "https://api.finbrain.tech/v2/screener/sentiment", headers=headers, params={"market": "NASDAQ", "limit": 10} ) result = response.json() for ticker in result["data"]["data"]: print(f"{ticker['symbol']}: {ticker['score']:.3f}") # Screen sentiment by region response = requests.get( "https://api.finbrain.tech/v2/screener/sentiment", headers=headers, params={"region": "US", "limit": 50} ) result = response.json() print(f"Average score: {result['data']['summary']['averageScore']:.3f}") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json screen_sentiment(const std::string& market, int limit, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { char* encoded_market = curl_easy_escape(curl, market.c_str(), 0); std::string url = "https://api.finbrain.tech/v2/screener/sentiment?market=" + std::string(encoded_market) + "&limit=" + std::to_string(limit); curl_free(encoded_market); struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = screen_sentiment("NASDAQ", 10, "YOUR_API_KEY"); for (auto& ticker : result["data"]["data"]) { std::cout << ticker["symbol"].get() << ": " << ticker["score"].get() << std::endl; } auto summary = result["data"]["summary"]; std::cout << "Average: " << summary["averageScore"].get() << std::endl; return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct ScreenerResponse { success: bool, data: ScreenerData, } #[derive(Debug, Deserialize)] struct ScreenerData { data: Vec, summary: SentimentSummary, } #[derive(Debug, Deserialize)] struct SentimentEntry { symbol: String, name: String, date: String, score: f64, } #[derive(Debug, Deserialize)] struct SentimentSummary { #[serde(rename = "totalTickers")] total_tickers: i64, #[serde(rename = "averageScore")] average_score: f64, #[serde(rename = "bullishCount")] bullish_count: i64, #[serde(rename = "bearishCount")] bearish_count: i64, #[serde(rename = "neutralCount")] neutral_count: i64, } fn screen_sentiment(market: &str, limit: i32, api_key: &str) -> Result> { let encoded_market = urlencoding::encode(market); let url = format!( "https://api.finbrain.tech/v2/screener/sentiment?market={}&limit={}", encoded_market, limit ); let client = Client::new(); let response: ScreenerResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = screen_sentiment("NASDAQ", 10, "YOUR_API_KEY")?; for entry in &result.data.data { println!("{}: {:.3}", entry.symbol, entry.score); } println!("Average: {:.3}", result.data.summary.average_score); Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/screener/sentiment?market=NASDAQ&limit=10", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const ticker of result.data.data) { console.log(`${ticker.symbol}: ${ticker.score}`); } console.log(`Average: ${result.data.summary.averageScore}`); ``` ### Insider Trading Screener [Section titled “Insider Trading Screener”](#insider-trading-screener) * cURL ```bash # Screen all recent insider trades curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/screener/insider-trading?limit=20" # Filter insider trades by market curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/screener/insider-trading?market=NASDAQ&limit=50" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Screen all recent insider trades response = requests.get( "https://api.finbrain.tech/v2/screener/insider-trading", headers=headers, params={"limit": 20} ) result = response.json() for trade in result["data"]["data"]: print(f"{trade['symbol']} - {trade['insider']}: " f"{trade['transactionType']} {trade['shares']} shares " f"(${trade['totalValue']:,.0f})") summary = result["data"]["summary"] print(f"\nTotal: {summary['totalTransactions']} transactions " f"({summary['buyCount']} buys, {summary['sellCount']} sells)") ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json screen_insider_trading(int limit, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/screener/insider-trading?limit=" + std::to_string(limit); struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = screen_insider_trading(20, "YOUR_API_KEY"); for (auto& trade : result["data"]["data"]) { std::cout << trade["symbol"].get() << " - " << trade["insider"].get() << ": " << trade["transactionType"].get() << " " << trade["shares"].get() << " shares" << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct InsiderScreenerResponse { success: bool, data: InsiderScreenerData, } #[derive(Debug, Deserialize)] struct InsiderScreenerData { data: Vec, summary: InsiderSummary, } #[derive(Debug, Deserialize)] struct InsiderTradeEntry { symbol: String, name: String, date: String, insider: String, relationship: String, #[serde(rename = "transactionType")] transaction_type: String, shares: i64, #[serde(rename = "totalValue")] total_value: i64, } #[derive(Debug, Deserialize)] struct InsiderSummary { #[serde(rename = "totalTransactions")] total_transactions: i64, #[serde(rename = "totalTickers")] total_tickers: i64, #[serde(rename = "buyCount")] buy_count: i64, #[serde(rename = "sellCount")] sell_count: i64, } fn screen_insider_trading(limit: i32, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/screener/insider-trading?limit={}", limit ); let client = Client::new(); let response: InsiderScreenerResponse = client .get(&url) .bearer_auth(api_key) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = screen_insider_trading(20, "YOUR_API_KEY")?; for trade in &result.data.data { println!("{} - {}: {} {} shares (${:.0})", trade.symbol, trade.insider, trade.transaction_type, trade.shares, trade.total_value); } println!("Total: {} transactions ({} buys, {} sells)", result.data.summary.total_transactions, result.data.summary.buy_count, result.data.summary.sell_count); Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/screener/insider-trading?limit=20", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); for (const trade of result.data.data) { console.log(`${trade.symbol} - ${trade.insider}: ${trade.transactionType} ${trade.shares} shares ($${trade.totalValue.toLocaleString()})`); } const { totalTransactions, buyCount, sellCount } = result.data.summary; console.log(`Total: ${totalTransactions} transactions (${buyCount} buys, ${sellCount} sells)`); ``` ## Responses [Section titled “Responses”](#responses) ### Sentiment Screener Response (200 OK) [Section titled “Sentiment Screener Response (200 OK)”](#sentiment-screener-response-200-ok) ```json { "success": true, "data": { "data": [ { "symbol": "VIV", "name": "Telefonica Brasil SA ADR", "date": "2026-01-19", "score": 0.644 }, { "symbol": "POWL", "name": "Powell Industries Inc", "date": "2026-01-19", "score": 0.406 } ], "summary": { "totalTickers": 2, "averageScore": 0.525, "bullishCount": 2, "bearishCount": 0, "neutralCount": 0 } }, "meta": { "timestamp": "2026-01-19T15:23:10.900Z" } } ``` ### Sentiment Screener Fields [Section titled “Sentiment Screener Fields”](#sentiment-screener-fields) | Field | Type | Description | | ---------------------- | ------- | ------------------------------------------------ | | `data[].symbol` | string | Stock ticker symbol | | `data[].name` | string | Company name | | `data[].date` | string | Date of the sentiment score (YYYY-MM-DD) | | `data[].score` | number | Sentiment score from -1 (bearish) to 1 (bullish) | | `summary.totalTickers` | integer | Number of tickers in the result | | `summary.averageScore` | number | Average sentiment score across all tickers | | `summary.bullishCount` | integer | Number of tickers with positive sentiment | | `summary.bearishCount` | integer | Number of tickers with negative sentiment | | `summary.neutralCount` | integer | Number of tickers with neutral sentiment | ### Insider Trading Screener Response (200 OK) [Section titled “Insider Trading Screener Response (200 OK)”](#insider-trading-screener-response-200-ok) ```json { "success": true, "data": { "data": [ { "symbol": "NVDA", "name": "Nvidia Corporation", "date": "2026-01-15", "insider": "Jensen Huang", "relationship": "CEO", "transactionType": "Sale", "shares": 120000, "totalValue": 15600000 } ], "summary": { "totalTransactions": 1, "totalTickers": 1, "buyCount": 0, "sellCount": 1 } }, "meta": { "timestamp": "2026-01-19T15:23:12.000Z" } } ``` ### Insider Trading Screener Fields [Section titled “Insider Trading Screener Fields”](#insider-trading-screener-fields) | Field | Type | Description | | --------------------------- | ------- | --------------------------------------------- | | `data[].symbol` | string | Stock ticker symbol | | `data[].name` | string | Company name | | `data[].date` | string | Transaction date (YYYY-MM-DD) | | `data[].insider` | string | Insider name | | `data[].relationship` | string | Insider’s role or relationship to the company | | `data[].transactionType` | string | Type of transaction (e.g., Sale, Buy) | | `data[].shares` | integer | Number of shares traded | | `data[].totalValue` | integer | Total transaction value in USD | | `summary.totalTransactions` | integer | Total number of transactions returned | | `summary.totalTickers` | integer | Number of unique tickers in the result | | `summary.buyCount` | integer | Number of buy transactions | | `summary.sellCount` | integer | Number of sell transactions | ## Usage Examples [Section titled “Usage Examples”](#usage-examples) ### Find Most Bullish Tickers [Section titled “Find Most Bullish Tickers”](#find-most-bullish-tickers) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/screener/sentiment", headers=headers, params={"market": "NASDAQ", "limit": 100} ) result = response.json() # Sort by sentiment score descending tickers = sorted(result["data"]["data"], key=lambda x: x["score"], reverse=True) print("Top 10 most bullish NASDAQ tickers:") for t in tickers[:10]: print(f" {t['symbol']:>6} ({t['name'][:30]:30}): {t['score']:.3f}") ``` ### Track Large Insider Purchases [Section titled “Track Large Insider Purchases”](#track-large-insider-purchases) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/screener/insider-trading", headers=headers, params={"limit": 500} ) result = response.json() # Filter for large purchases only large_buys = [ t for t in result["data"]["data"] if t["transactionType"] == "Purchase" and t["totalValue"] >= 1_000_000 ] print(f"Large insider purchases (above $1M):") for trade in large_buys: print(f" {trade['symbol']:>6} - {trade['insider']}: " f"${trade['totalValue']:>12,.0f} ({trade['shares']:,} shares)") ``` ### Screen Congressional Trading Activity [Section titled “Screen Congressional Trading Activity”](#screen-congressional-trading-activity) ```python from datetime import date import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Screen House trades house = requests.get( "https://api.finbrain.tech/v2/screener/congress/house", headers=headers, params={"limit": 100} ).json() # Screen Senate trades senate = requests.get( "https://api.finbrain.tech/v2/screener/congress/senate", headers=headers, params={"limit": 100} ).json() print(f"Recent House trades: {len(house['data']['data'])}") print(f"Recent Senate trades: {len(senate['data']['data'])}") # Reporting lag, straight from the two dates on each row for t in house["data"]["data"][:10]: if t["disclosureDate"]: lag = (date.fromisoformat(t["disclosureDate"]) - date.fromisoformat(t["date"])).days print(f" {t['symbol']:>6} - {t['politician']}: disclosed after {lag} days") ``` ### Congressional Screener Response (200 OK) [Section titled “Congressional Screener Response (200 OK)”](#congressional-screener-response-200-ok) ```json { "success": true, "data": { "chamber": "house", "data": [ { "symbol": "NVDA", "name": "Nvidia Corporation", "date": "2026-01-10", "politician": "Nancy Pelosi", "transactionType": "Purchase", "amount": "$1,000,001 - $5,000,000", "owner": "SP", "disclosureDate": "2026-01-28" } ], "summary": { "totalTrades": 1, "totalTickers": 1, "totalPoliticians": 1, "buyCount": 1, "sellCount": 0 } }, "meta": { "timestamp": "2026-01-19T15:23:12.000Z" } } ``` The Senate endpoint returns the same structure with `"chamber": "senate"`. ### Congressional Screener Fields [Section titled “Congressional Screener Fields”](#congressional-screener-fields) | Field | Type | Description | | -------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data.chamber` | string | Congressional chamber (`house` or `senate`) | | `data[].symbol` | string | Stock ticker symbol | | `data[].name` | string | Company name | | `data[].date` | string | Transaction date (YYYY-MM-DD) | | `data[].politician` | string | Name of the House or Senate member | | `data[].transactionType` | string | Transaction type (Purchase or Sale) | | `data[].amount` | string | Transaction amount (exact value or range) | | `data[].owner` | string or null | Beneficial owner of the account: `SELF`, `SP` (spouse), `DC` (dependent child), `JT` (joint), a member-specific account code, or `UNKNOWN` for blank Senate filings | | `data[].disclosureDate` | string or null | Date the trade was publicly disclosed (YYYY-MM-DD). Nullable, but nulls are rare — historical rows were backfilled | | `summary.totalTrades` | integer | Total number of trades returned | | `summary.totalTickers` | integer | Number of unique tickers in the result | | `summary.totalPoliticians` | integer | Number of unique members in the result | | `summary.buyCount` | integer | Number of purchase transactions | | `summary.sellCount` | integer | Number of sale transactions | ### Corporate Lobbying Screener Response (200 OK) [Section titled “Corporate Lobbying Screener Response (200 OK)”](#corporate-lobbying-screener-response-200-ok) ```json { "success": true, "data": { "data": [ { "company": "AAPL", "companyName": "Apple Inc.", "date": "2025-09-15", "registrantName": "Fierce Government Relations", "income": 150000, "expenses": 0, "quarter": "Q3" } ], "summary": { "totalFilings": 1, "totalCompanies": 1, "totalSpend": 150000 } }, "meta": { "timestamp": "2026-03-12T12:00:00.000Z" } } ``` ### Corporate Lobbying Screener Fields [Section titled “Corporate Lobbying Screener Fields”](#corporate-lobbying-screener-fields) | Field | Type | Description | | ------------------------ | ------- | ------------------------------------------- | | `data[].company` | string | Stock ticker symbol | | `data[].companyName` | string | Company name | | `data[].date` | string | Filing date (YYYY-MM-DD) | | `data[].registrantName` | string | Lobbying firm name | | `data[].income` | number | Income reported (USD) | | `data[].expenses` | number | Expenses reported (USD) | | `data[].quarter` | string | Filing quarter (Q1-Q4) | | `summary.totalFilings` | integer | Total number of filings returned | | `summary.totalCompanies` | integer | Number of unique companies | | `summary.totalSpend` | number | Sum of income + expenses across all filings | ### Government Contracts Screener Response (200 OK) [Section titled “Government Contracts Screener Response (200 OK)”](#government-contracts-screener-response-200-ok) ```json { "success": true, "data": { "data": [ { "symbol": "LMT", "name": "Lockheed Martin Corporation", "awardId": "CONT_AWD_0001", "awardAmount": 50000000, "recipientName": "Lockheed Martin Corporation", "startDate": "2025-06-01", "awardingAgency": "Department of Defense", "naicsDescription": "Aircraft Manufacturing" } ], "summary": { "totalContracts": 150, "totalTickers": 45, "totalValue": 2500000000 } }, "meta": { "timestamp": "2026-03-17T15:05:59.853Z" } } ``` ### Government Contracts Screener Fields [Section titled “Government Contracts Screener Fields”](#government-contracts-screener-fields) | Field | Type | Description | | ------------------------- | ------- | ----------------------------------- | | `data[].symbol` | string | Stock ticker symbol | | `data[].name` | string | Company name | | `data[].awardId` | string | Unique contract award identifier | | `data[].awardAmount` | number | Total award value in USD | | `data[].recipientName` | string | Company receiving the contract | | `data[].startDate` | string | Contract start date (YYYY-MM-DD) | | `data[].awardingAgency` | string | Federal agency issuing the contract | | `data[].naicsDescription` | string | NAICS industry description | | `summary.totalContracts` | integer | Total number of contracts returned | | `summary.totalTickers` | integer | Number of unique tickers | | `summary.totalValue` | number | Sum of all award amounts (USD) | ### Reddit Mentions Screener Response (200 OK) [Section titled “Reddit Mentions Screener Response (200 OK)”](#reddit-mentions-screener-response-200-ok) ```json { "success": true, "data": { "data": [ { "symbol": "TSLA", "name": "Tesla, Inc.", "date": "2026-03-16T14:00:00.000Z", "totalMentions": 57, "subreddits": { "wallstreetbets": 45, "stocks": 12 } } ], "summary": { "totalEntries": 1, "totalTickers": 1, "averageMentions": 57, "topMentioned": ["TSLA"], "subredditNames": ["stocks", "wallstreetbets"] } }, "meta": { "timestamp": "2026-03-17T15:05:59.853Z" } } ``` ### Reddit Mentions Screener Fields [Section titled “Reddit Mentions Screener Fields”](#reddit-mentions-screener-fields) | Field | Type | Description | | ------------------------- | ------- | -------------------------------------- | | `data[].symbol` | string | Stock ticker symbol | | `data[].name` | string | Company name | | `data[].date` | string | Snapshot timestamp (ISO 8601) | | `data[].totalMentions` | integer | Total mentions across all subreddits | | `data[].subreddits` | object | Mention counts keyed by subreddit name | | `summary.totalEntries` | integer | Total entries returned | | `summary.totalTickers` | integer | Unique tickers in result | | `summary.averageMentions` | number | Average mentions per entry | | `summary.topMentioned` | array | Top tickers by mention count | | `summary.subredditNames` | array | List of subreddit names in data | ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid parameters or missing required market/region | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Endpoint not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [News Sentiment API](/api-reference/sentiment/) - Get sentiment for a single ticker * [Insider Transactions API](/api-reference/insider-transactions/) - Get insider trades for a single ticker * [Congressional Trading API](/api-reference/congressional-trading/) - Get House and Senate trades for a single ticker * [Analyst Ratings API](/api-reference/analyst-ratings/) - Get analyst ratings for a single ticker * [Government Contracts API](/api-reference/government-contracts/) - Get government contracts for a single ticker * [Reddit Mentions API](/api-reference/reddit-mentions/) - Get Reddit mentions for a single ticker * [Recent Data API](/api-reference/recent/) - Get the most recent data entries across all tickers # News Sentiment API > API reference for the FinBrain sentiments endpoint. Retrieve AI-powered sentiment analysis scores for stock tickers. Retrieve AI-powered sentiment analysis scores derived from financial news. Get sentiment scores for any ticker. ## Endpoint [Section titled “Endpoint”](#endpoint) ```plaintext GET /v2/sentiment/{symbol} ``` ## Authentication [Section titled “Authentication”](#authentication) Supports multiple authentication methods (in order of preference): | Method | Example | | -------------------------- | ------------------------------------ | | Bearer token (recommended) | `Authorization: Bearer YOUR_API_KEY` | | X-API-Key header | `X-API-Key: YOUR_API_KEY` | | Query parameter | `?apiKey=YOUR_API_KEY` | | Legacy query parameter | `?token=YOUR_API_KEY` | ## Parameters [Section titled “Parameters”](#parameters) ### Path Parameters [Section titled “Path Parameters”](#path-parameters) | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------ | | `symbol` | string | Yes | Stock ticker symbol (e.g., `AAPL`, `MSFT`) | ### Query Parameters [Section titled “Query Parameters”](#query-parameters) | Parameter | Type | Required | Description | | ----------- | ------- | -------- | --------------------------------------- | | `apiKey` | string | No | Your API key (if not using header auth) | | `startDate` | string | No | Start date (YYYY-MM-DD) | | `endDate` | string | No | End date (YYYY-MM-DD) | | `limit` | integer | No | Maximum number of results to return | ## Request [Section titled “Request”](#request) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.sentiments.ticker("AAPL", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(df) ``` * cURL ```bash # Get sentiment data curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/sentiment/AAPL" # With date range and limit curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/sentiment/AAPL?startDate=2026-01-01&endDate=2026-01-31&limit=30" ``` * Python (requests) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} # Get sentiment data response = requests.get( "https://api.finbrain.tech/v2/sentiment/AAPL", headers=headers ) result = response.json() # With date range and limit response = requests.get( "https://api.finbrain.tech/v2/sentiment/AAPL", headers=headers, params={"startDate": "2026-01-01", "endDate": "2026-01-31", "limit": 30} ) result = response.json() ``` * C++ ```cpp #include #include #include #include using json = nlohmann::json; size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { userp->append((char*)contents, size * nmemb); return size * nmemb; } json get_sentiment(const std::string& symbol, const std::string& api_key) { CURL* curl = curl_easy_init(); std::string response; if (curl) { std::string url = "https://api.finbrain.tech/v2/sentiment/" + symbol; struct curl_slist* headers = nullptr; std::string auth_header = "Authorization: Bearer " + api_key; headers = curl_slist_append(headers, auth_header.c_str()); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } return json::parse(response); } int main() { auto result = get_sentiment("AAPL", "YOUR_API_KEY"); auto data = result["data"]; std::cout << "Symbol: " << data["symbol"].get() << " (" << data["name"].get() << ")" << std::endl; for (auto& entry : data["data"]) { std::cout << entry["date"].get() << ": " << entry["score"].get() << std::endl; } return 0; } ``` * Rust ```rust use reqwest::blocking::Client; use reqwest::header::{AUTHORIZATION, HeaderValue}; use serde::Deserialize; use std::error::Error; #[derive(Debug, Deserialize)] struct ApiResponse { success: bool, data: SentimentData, } #[derive(Debug, Deserialize)] struct SentimentData { symbol: String, name: String, data: Vec, } #[derive(Debug, Deserialize)] struct SentimentEntry { date: String, score: f64, } fn get_sentiment(symbol: &str, api_key: &str) -> Result> { let url = format!( "https://api.finbrain.tech/v2/sentiment/{}", symbol ); let client = Client::new(); let response: ApiResponse = client .get(&url) .header(AUTHORIZATION, HeaderValue::from_str(&format!("Bearer {}", api_key))?) .send()? .json()?; Ok(response) } fn main() -> Result<(), Box> { let result = get_sentiment("AAPL", "YOUR_API_KEY")?; let data = result.data; println!("Symbol: {} ({})", data.symbol, data.name); for entry in &data.data { println!("{}: {:.3}", entry.date, entry.score); } Ok(()) } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/sentiment/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const result = await response.json(); console.log(result.data); ``` ## Response [Section titled “Response”](#response) ### Success Response (200 OK) [Section titled “Success Response (200 OK)”](#success-response-200-ok) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "data": [ { "date": "2026-01-19", "score": 0.265 }, { "date": "2026-01-16", "score": 0.346 }, { "date": "2026-01-15", "score": 0.279 }, { "date": "2026-01-14", "score": 0.17 }, { "date": "2026-01-13", "score": 0.128 } ] }, "meta": { "timestamp": "2026-01-19T15:06:13.240Z" } } ``` ### Response Fields [Section titled “Response Fields”](#response-fields) | Field | Type | Description | | --------- | ------- | ---------------------------------- | | `success` | boolean | Whether the request was successful | | `data` | object | Sentiment data container | | `meta` | object | Response metadata | ### Data Object Fields [Section titled “Data Object Fields”](#data-object-fields) | Field | Type | Description | | -------- | ------ | -------------------------------- | | `symbol` | string | Stock ticker symbol | | `name` | string | Company name | | `data` | array | Array of sentiment score entries | ### Sentiment Entry Fields [Section titled “Sentiment Entry Fields”](#sentiment-entry-fields) Each item in the `data` array contains: | Field | Type | Description | | ------- | ------ | ------------------------------------------------ | | `date` | string | Date of the sentiment score (YYYY-MM-DD) | | `score` | number | Sentiment score from -1 (bearish) to 1 (bullish) | ## Sentiment Score Interpretation [Section titled “Sentiment Score Interpretation”](#sentiment-score-interpretation) | Score Range | Interpretation | | ------------ | -------------------------- | | 0.5 to 1.0 | Strong bullish sentiment | | 0.2 to 0.5 | Moderate bullish sentiment | | -0.2 to 0.2 | Neutral sentiment | | -0.5 to -0.2 | Moderate bearish sentiment | | -1.0 to -0.5 | Strong bearish sentiment | ## Usage Examples [Section titled “Usage Examples”](#usage-examples) ### Basic Sentiment Check [Section titled “Basic Sentiment Check”](#basic-sentiment-check) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} response = requests.get( "https://api.finbrain.tech/v2/sentiment/AAPL", headers=headers ) result = response.json() entries = result["data"]["data"] # Get latest sentiment (first entry in array) latest = entries[0] score = latest["score"] if score > 0.5: print(f"AAPL sentiment is strongly bullish: {score:.3f}") elif score > 0: print(f"AAPL sentiment is mildly bullish: {score:.3f}") elif score > -0.5: print(f"AAPL sentiment is mildly bearish: {score:.3f}") else: print(f"AAPL sentiment is strongly bearish: {score:.3f}") ``` ### Detect Sentiment Spikes [Section titled “Detect Sentiment Spikes”](#detect-sentiment-spikes) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} def detect_sentiment_spike(symbol): """Detect unusual sentiment activity""" response = requests.get( f"https://api.finbrain.tech/v2/sentiment/{symbol}", headers=headers ) result = response.json() entries = result["data"]["data"] if len(entries) < 10: return None # Calculate baseline from historical data historical_scores = [e["score"] for e in entries[1:10]] avg_score = sum(historical_scores) / len(historical_scores) # Compare to latest latest_score = entries[0]["score"] score_change = latest_score - avg_score alerts = [] if abs(score_change) > 0.2: direction = "improved" if score_change > 0 else "declined" alerts.append(f"Sentiment {direction} significantly ({score_change:+.3f})") return alerts alerts = detect_sentiment_spike("TSLA") if alerts: print("Sentiment Alerts:") for alert in alerts: print(f" - {alert}") ``` ### Sentiment Trend Analysis [Section titled “Sentiment Trend Analysis”](#sentiment-trend-analysis) ```python import requests headers = {"Authorization": "Bearer YOUR_API_KEY"} def analyze_sentiment_trend(symbol, days=14): """Analyze sentiment trend over time""" response = requests.get( f"https://api.finbrain.tech/v2/sentiment/{symbol}", headers=headers, params={"limit": days} ) result = response.json() entries = result["data"]["data"] if len(entries) < days: return None recent = entries[:days//2] older = entries[days//2:days] recent_avg = sum(e["score"] for e in recent) / len(recent) older_avg = sum(e["score"] for e in older) / len(older) change = recent_avg - older_avg if change > 0.1: trend = "improving" elif change < -0.1: trend = "deteriorating" else: trend = "stable" return { "symbol": symbol, "recent_sentiment": recent_avg, "older_sentiment": older_avg, "change": change, "trend": trend } result = analyze_sentiment_trend("NVDA") print(f"Sentiment trend: {result['trend']} ({result['change']:+.3f})") ``` ## Errors [Section titled “Errors”](#errors) | Code | Error | Description | | ---- | --------------------- | --------------------------------------------------------- | | 400 | Bad Request | Invalid symbol | | 401 | Unauthorized | Invalid or missing API key | | 403 | Forbidden | Authenticated, but not authorized to access this resource | | 404 | Not Found | Ticker not found | | 429 | Too Many Requests | Rate limit exceeded — wait and retry | | 500 | Internal Server Error | Server-side error | ## Related [Section titled “Related”](#related) * [News Sentiment Dataset](/datasets/sentiment/) - Use cases and analysis examples * [Price Forecasts](/api-reference/ai-forecasts/) - Get price forecasts * [Analyst Ratings](/api-reference/analyst-ratings/) - Get analyst recommendations * [Put/Call Data](/api-reference/put-call/) - Get options sentiment # Price Forecasts Dataset > Access quantitative stock price forecasts via REST API. Daily and monthly predictions with confidence intervals, generated from ARIMA time-series models. Access quantitative price forecasts for over 28,000 tickers. FinBrain’s time-series models produce daily and monthly predictions with calibrated confidence intervals and directional signals, ready to plug into research pipelines and production systems. ## Methodology [Section titled “Methodology”](#methodology) FinBrain price forecasts are generated using **ARIMA (AutoRegressive Integrated Moving Average)** time-series models. ARIMA captures the statistical structure of historical price movements — trends, seasonality, and autocorrelation — and produces out-of-sample forecasts with calibrated confidence intervals. We previously explored deep learning architectures (including shallow recurrent networks), but found that their tendency to overfit noisy financial time series produced less reliable out-of-sample forecasts than well-calibrated statistical models. ARIMA is a transparent, rigorously studied methodology with decades of academic validation in financial forecasting. **Key properties:** * Produces point estimates (`mid`) with lower and upper bounds representing confidence intervals * Calibrated on rolling historical windows to reflect current market conditions * Updated daily for all covered tickers before market open * Directional signals (`expectedShortTerm`, `expectedMidTerm`, `expectedLongTerm`) derived from the forecast path Forecasts are probabilistic estimates based on historical patterns. They are not guarantees of future performance and should be used alongside other data and analysis. ## What’s Included [Section titled “What’s Included”](#whats-included) The Price Forecasts dataset provides: * **Price Forecasts**: Predicted price (`mid`) with `lower` and `upper` bounds for each future date * **Expected Moves**: Short, mid, and long-term expected percentage changes * **Bound Changes**: Lower and upper bound percentage changes * **Daily & Monthly Types**: Choose your forecast horizon ## Coverage [Section titled “Coverage”](#coverage) Price forecasts are generated daily for every ticker in every covered market. Total coverage is approximately **28,000+ tickers across 20 global markets**. ### United States [Section titled “United States”](#united-states) | Market | Tickers | | ---------- | ------- | | NYSE | 6,000+ | | NASDAQ | 5,500+ | | ETFs | 750+ | | S\&P 500 | 500+ | | OTC Market | 300+ | | DOW 30 | 30 | ### International Equities [Section titled “International Equities”](#international-equities) | Market | Region | Tickers | | ------------------- | ------------ | ------- | | Canada TSX | Americas | 2,500+ | | Brazil BOVESPA | Americas | 2,000+ | | Mexico BMV | Americas | 600+ | | Hong Kong Hang Seng | Asia-Pacific | 3,500+ | | Australia ASX | Asia-Pacific | 2,000+ | | Russia MOEX | Europe | 350+ | | UK FTSE 100 | Europe | 100 | | Germany DAX | Europe | 30 | | Israel TASE | Middle East | 850+ | | Saudi Arabia TASI | Middle East | 350+ | ### Global [Section titled “Global”](#global) | Market | Tickers | | ---------------- | ------- | | Foreign Exchange | 900+ | | Index Futures | 750+ | | Commodities | 150+ | | Cryptocurrencies | 120+ | All forecasts update **daily before market open**. The dataset is delivered point-in-time — each request returns the most recent forward-looking forecast. Historical forecasts are not exposed via the API; users who require a forecast archive should persist the daily output as part of their pipeline. ## Understanding Forecasts [Section titled “Understanding Forecasts”](#understanding-forecasts) ### Expected Move Fields [Section titled “Expected Move Fields”](#expected-move-fields) | Field | Daily Forecasts | Monthly Forecasts | | ---------------------------- | ---------------------- | ------------------------ | | `metadata.expectedShortTerm` | 3-day expected % move | 3-month expected % move | | `metadata.expectedMidTerm` | 5-day expected % move | 6-month expected % move | | `metadata.expectedLongTerm` | 10-day expected % move | 12-month expected % move | ### Forecast Objects [Section titled “Forecast Objects”](#forecast-objects) Each forecast in the `predictions` array contains structured fields: ```json { "date": "2024-11-04", "mid": 201.33, "lower": 197.21, "upper": 205.45 } ``` * `mid`: Predicted price * `lower`: Lower bound of the confidence interval * `upper`: Upper bound of the confidence interval All numeric values are returned as **numbers** (not strings). ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.predictions.ticker("AAPL", prediction_type="daily", as_dataframe=True) print(df) # mid lower upper # date # 2024-11-04 201.33 197.21 205.45 ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" headers = {"Authorization": f"Bearer {API_KEY}"} # Get daily price forecasts for AAPL response = requests.get(f"{BASE_URL}/predictions/daily/AAPL", headers=headers) result = response.json() predictions = result["data"]["predictions"] for p in predictions: print(f"{p['date']}: mid={p['mid']}, lower={p['lower']}, upper={p['upper']}") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the API Reference for [Price Forecasts API](/api-reference/ai-forecasts/). ## Visualization [Section titled “Visualization”](#visualization) Plot price forecasts with the built-in SDK chart: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # One-line interactive chart with confidence bands fb.plot.predictions("AAPL") ``` ![Price Forecast Chart](/_astro/ai-price-forecast-chart-python.DhVzK-o7.png) AAPL price forecasts with confidence bounds ## Use Cases [Section titled “Use Cases”](#use-cases) ### Systematic Trading Signals [Section titled “Systematic Trading Signals”](#systematic-trading-signals) Build trading systems that generate buy/sell signals based on forecast expectations: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def get_trading_signal(symbol, threshold=1.0): """Check if a ticker has a strong expected move""" result = fb.predictions.ticker(symbol, prediction_type="daily") expected = result["metadata"]["expectedShortTerm"] # 3-day expected move if expected > threshold: return "bullish", expected elif expected < -threshold: return "bearish", expected else: return "neutral", expected # Screen a watchlist watchlist = ["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA"] for symbol in watchlist: try: signal, expected = get_trading_signal(symbol) if signal != "neutral": print(f"{symbol}: {signal} ({expected:+.2f}%)") except Exception: continue ``` ### Portfolio Screening [Section titled “Portfolio Screening”](#portfolio-screening) Filter your investment universe based on expected price movements: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def screen_portfolio(symbols, min_expected=0.5): """Screen portfolio for positive expected moves""" opportunities = [] for symbol in symbols: try: result = fb.predictions.ticker(symbol, prediction_type="daily") metadata = result["metadata"] expected_3day = metadata["expectedShortTerm"] if expected_3day > min_expected: opportunities.append({ "symbol": symbol, "expected_3day": expected_3day, "expected_5day": metadata["expectedMidTerm"], "expected_10day": metadata["expectedLongTerm"] }) except Exception: continue return sorted(opportunities, key=lambda x: x["expected_3day"], reverse=True) # Screen tech stocks watchlist = ["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA"] opportunities = screen_portfolio(watchlist) for opp in opportunities: print(f"{opp['symbol']}: {opp['expected_3day']:.2f}% (3-day), {opp['expected_5day']:.2f}% (5-day)") ``` ### Multi-Horizon Analysis [Section titled “Multi-Horizon Analysis”](#multi-horizon-analysis) Compare short, mid, and long-term expectations to identify momentum: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def analyze_momentum(symbol): """Analyze if momentum is accelerating or decelerating""" result = fb.predictions.ticker(symbol, prediction_type="daily") metadata = result["metadata"] short = metadata["expectedShortTerm"] # 3-day mid = metadata["expectedMidTerm"] # 5-day long_term = metadata["expectedLongTerm"] # 10-day # Check if expectations are increasing across time horizons if short > 0 and mid > short and long_term > mid: return "accelerating_bullish" elif short < 0 and mid < short and long_term < mid: return "accelerating_bearish" elif short > 0 and mid > 0 and long_term > 0: return "bullish" elif short < 0 and mid < 0 and long_term < 0: return "bearish" else: return "mixed" momentum = analyze_momentum("AAPL") print(f"AAPL momentum: {momentum}") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Price Forecasts API Reference](/api-reference/ai-forecasts/) - Single ticker endpoint * [News Sentiment](/datasets/sentiment/) - Combine with sentiment data # Analyst Ratings Dataset > Access Wall Street analyst ratings and price targets via REST API. Track buy/sell recommendations and target prices for systematic trading. Access Wall Street analyst ratings, price targets, and recommendation changes. Track consensus ratings and target price movements for systematic trading strategies. ## What’s Included [Section titled “What’s Included”](#whats-included) The Analyst Ratings dataset provides: * **Current Rating**: Buy, hold, or sell recommendation * **Price Target**: Analyst’s target price (with historical changes) * **Analyst Info**: Firm name and rating action * **Rating Changes**: Upgrades, downgrades, and reiterations * **Historical Data**: Track rating changes over time ## Coverage [Section titled “Coverage”](#coverage) | Coverage | Details | | ---------------- | ----------------------------------------- | | Markets | S\&P 500, NASDAQ, NYSE | | Sources | Major investment banks and research firms | | Update Frequency | Daily | | Historical Data | 3+ years | ## Rating Categories [Section titled “Rating Categories”](#rating-categories) | Rating | Meaning | Signal | | ---------------- | --------------------------------- | ------- | | Strong Buy | Highest conviction recommendation | Bullish | | Buy / Outperform | Expect stock to beat market | Bullish | | Hold / Neutral | Expect market performance | Neutral | | Underperform | Expect stock to lag market | Bearish | | Sell | Recommend selling | Bearish | Note: The `targetPrice` field is a **string** (e.g., `"$275"`). ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.analyst_ratings.ticker("AAPL", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get(f"{BASE_URL}/v2/analyst-ratings/AAPL", headers=headers) result = response.json() # Access ratings from the response envelope ratings = result["data"]["ratings"] for r in ratings[:5]: print(f"{r['date']}: {r['institution']} - {r['rating']} (Target: {r['targetPrice']})") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/analyst-ratings/). ## Use Cases [Section titled “Use Cases”](#use-cases) ### Upgrade/Downgrade Scanner [Section titled “Upgrade/Downgrade Scanner”](#upgradedowngrade-scanner) Scan for recent rating changes: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def scan_rating_changes(tickers): """Find stocks with recent upgrades or downgrades""" upgrades = [] downgrades = [] for symbol in tickers: try: df = fb.analyst_ratings.ticker(symbol, as_dataframe=True) for _, row in df.head(5).iterrows(): # Last 5 ratings if row["action"] == "Upgrade": upgrades.append({ "symbol": symbol, "institution": row["institution"], "rating": row["rating"], "targetPrice": row["targetPrice"], "date": row.name }) elif row["action"] == "Downgrade": downgrades.append({ "symbol": symbol, "institution": row["institution"], "rating": row["rating"], "targetPrice": row["targetPrice"], "date": row.name }) except Exception: continue return {"upgrades": upgrades, "downgrades": downgrades} tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA"] changes = scan_rating_changes(tickers) print("Recent Upgrades:") for u in changes["upgrades"]: print(f" {u['symbol']}: {u['institution']} -> {u['rating']} ({u['targetPrice']})") print("\nRecent Downgrades:") for d in changes["downgrades"]: print(f" {d['symbol']}: {d['institution']} -> {d['rating']} ({d['targetPrice']})") ``` ### Price Target Upside [Section titled “Price Target Upside”](#price-target-upside) Calculate upside potential to consensus target: ```python import re from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def parse_target_price(target_str): """Parse target price string like '$275' and return numeric value""" if not target_str: return None # Match price patterns like $190, $205.50, etc. prices = re.findall(r'\$?([\d,]+\.?\d*)', str(target_str).replace(',', '')) if prices: # Return the last price (new target) or only price return float(prices[-1]) return None def calculate_upside(symbol, current_price): """Calculate upside to analyst target""" df = fb.analyst_ratings.ticker(symbol, as_dataframe=True) if df.empty: return None # Parse target prices from string format targets = [] for target_str in df["targetPrice"]: target = parse_target_price(target_str) if target: targets.append(target) if not targets: return None avg_target = sum(targets) / len(targets) upside = ((avg_target - current_price) / current_price) * 100 return { "symbol": symbol, "current_price": current_price, "avg_target_price": round(avg_target, 2), "upside_percent": round(upside, 2), "num_analysts": len(targets) } # Example usage (you'd get current price from market data) result = calculate_upside("AAPL", 185.00) if result: print(f"{result['symbol']}: {result['upside_percent']}% upside to ${result['avg_target_price']}") ``` ### Consensus Trend Analysis [Section titled “Consensus Trend Analysis”](#consensus-trend-analysis) Track how analyst sentiment is changing over time: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def analyze_rating_trend(symbol): """Analyze if analyst sentiment is improving or deteriorating""" df = fb.analyst_ratings.ticker(symbol, as_dataframe=True) rating_scores = { "Sell": 1, "Underperform": 2, "Hold": 3, "Neutral": 3, "Buy": 4, "Outperform": 4, "Overweight": 4, "Strong Buy": 5 } df["score"] = df["rating"].map(rating_scores).fillna(3) if len(df) < 2: return "insufficient_data" recent_avg = df["score"].head(5).mean() older_avg = df["score"].iloc[5:10].mean() if len(df) > 5 else recent_avg if recent_avg > older_avg + 0.3: return "improving" elif recent_avg < older_avg - 0.3: return "deteriorating" else: return "stable" trend = analyze_rating_trend("AAPL") print(f"Analyst sentiment: {trend}") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Analyst Ratings API Reference](/api-reference/analyst-ratings/) - Endpoint details, parameters, and response schema * [Price Forecasts](/datasets/ai-forecasts/) - Combine with forecasts * [News Sentiment](/datasets/sentiment/) - Market sentiment data # App Ratings Dataset > Access App Store and Play Store ratings via REST API. Every app a company publishes, each with its own history, as alternative data for consumer-facing companies. Access mobile app store ratings and review data from Apple App Store and Google Play Store. Track app performance metrics as alternative data signals for consumer-facing companies. ## What’s Included [Section titled “What’s Included”](#whats-included) The App Ratings dataset provides: * **iOS Ratings**: App Store rating (1-5 stars) and ratings count * **Android Ratings**: Play Store rating (1-5 stars), ratings count, and install count * **Every App, Identified**: each app a company publishes arrives as its own series, keyed by store app id and carrying the app’s published title * **Rating Changes**: Track rating movements over time * **Daily Snapshots**: every app, every day, at a fixed UTC time * **Day-over-day Movement**: consecutive daily snapshots per app, so ratings growth and install growth are a one-line difference ## Coverage [Section titled “Coverage”](#coverage) | Coverage | Details | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Platforms | Apple App Store, Google Play Store | | Companies | Companies publishing mobile apps under a covered ticker | | Apps per company | Every app we can attribute to the issuer, not just its flagship | | Update Frequency | Daily, collected at 03:00 UTC | | Historical Data | From 3 September 2026, the day daily per-app collection began. Nothing earlier is served. An app added to the registry later starts on the day it was added and is never backfilled | Note: `installCount` is Play Store only — Apple publishes no install count, so it is always `null` on iOS. ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.app_ratings.ticker("UBER", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get(f"{BASE_URL}/v2/app-ratings/UBER", headers=headers) result = response.json() # The envelope is {success, data, meta}; the series lives at data.data for entry in result["data"]["data"][:5]: # Either side is None when there is no rated app on that store ios = entry["ios"] or {} android = entry["android"] or {} print(f"{entry['date']}: iOS {ios.get('score')} | Android {android.get('score')}") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/app-ratings/). ## Every App, Not Just the Flagship [Section titled “Every App, Not Just the Flagship”](#every-app-not-just-the-flagship) Most companies do not publish one app. A retailer ships a shopping app, a payments app and a loyalty app; a bank ships retail banking, business banking and a card app; Apple publishes over a hundred on iOS alone. Collapsing that to a single company score throws away most of the signal — and hides which product line is actually moving. Each response therefore carries **one series per app per platform**, identified by its store app id and title, alongside the company-level view: | View | What it reports | | --------------------------------- | --------------------------------------------------------- | | Blended (`data`, the SDK default) | The company’s biggest app on each store, one row per date | | Per-app (`apps`, `per_app=True`) | Every app, each with its own history | There is deliberately **no blended company score**. Weighting a portfolio of apps into one number is a judgement — by ratings volume, by revenue relevance, by product line — and it belongs to the desk making the trade, not to the data provider. You get the parts; you decide the weights. ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # One row per app per observation apps = fb.app_ratings.ticker("AAPL", as_dataframe=True, per_app=True) # The company's app portfolio, biggest first portfolio = ( apps.groupby(["platform", "app_id", "app_name"])["ratings_count"] .max() .sort_values(ascending=False) ) print(portfolio.head(10)) # Track one product line on its own (Shazam on iOS) shazam = apps[apps["app_id"] == "284993459"].sort_values("date") print(shazam[["date", "score", "ratings_count"]].tail()) ``` Two things to know when you work with the per-app frame: * It is **not indexed by date** — a single date carries one row per app, so a date index would not be unique. * Every row carries an `app_id`: records have been keyed per app since collection restarted on 3 September 2026, and nothing older is served. * The app registry is reviewed continuously. An app added later starts its series on the day it was added; earlier dates are never backfilled, so the first observation is the day FinBrain began tracking that app. ## Visualization [Section titled “Visualization”](#visualization) Plot app ratings with the built-in SDK chart: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Interactive chart: ratings count (bars) + score (line) fb.plot.app_ratings("UBER", store="app") # iOS App Store fb.plot.app_ratings("UBER", store="play") # Google Play Store # Chart one specific app instead of the company's biggest on that store. # Ids come from the per-app frame above; the app must live on that store. fb.plot.app_ratings("AAPL", store="app", app_id="284993459") ``` ![App Ratings Chart](/_astro/app-ratings-chart-python.BVCSpOsr.png) UBER App Store ratings over time ## Interpreting App Ratings [Section titled “Interpreting App Ratings”](#interpreting-app-ratings) ### Rating Levels [Section titled “Rating Levels”](#rating-levels) | Rating | Interpretation | Signal | | --------- | -------------- | ------------------------ | | 4.5 - 5.0 | Excellent | Strong user satisfaction | | 4.0 - 4.5 | Good | Healthy app performance | | 3.5 - 4.0 | Average | Room for improvement | | 3.0 - 3.5 | Below average | User concerns | | < 3.0 | Poor | Significant issues | ### Rating Trends [Section titled “Rating Trends”](#rating-trends) | Trend | Interpretation | | ---------------------------------- | -------------------------- | | Rising rating | Improving product/service | | Stable rating | Consistent experience | | Falling rating | Potential issues emerging | | Rating divergence (iOS vs Android) | Platform-specific problems | ## Use Cases [Section titled “Use Cases”](#use-cases) ### App Quality Monitor [Section titled “App Quality Monitor”](#app-quality-monitor) Monitor app ratings for quality signals: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def monitor_app_quality(symbol): """Monitor app quality and detect rating changes""" df = fb.app_ratings.ticker(symbol, as_dataframe=True) if df.empty or len(df) < 7: return None ios_change = df["ios_score"].iloc[0] - df["ios_score"].iloc[6] android_change = df["android_score"].iloc[0] - df["android_score"].iloc[6] alerts = [] if ios_change < -0.1: alerts.append(f"App Store rating dropped {abs(ios_change):.2f}") if android_change < -0.1: alerts.append(f"Play Store rating dropped {abs(android_change):.2f}") if df["ios_score"].iloc[0] < 4.0: alerts.append(f"App Store rating below 4.0 ({df['ios_score'].iloc[0]:.1f})") if df["android_score"].iloc[0] < 4.0: alerts.append(f"Play Store rating below 4.0 ({df['android_score'].iloc[0]:.1f})") return { "symbol": symbol, "current_ios": df["ios_score"].iloc[0], "current_android": df["android_score"].iloc[0], "ios_change_7d": ios_change, "android_change_7d": android_change, "alerts": alerts, "status": "warning" if alerts else "healthy" } result = monitor_app_quality("UBER") print(f"Status: {result['status']}") if result["alerts"]: print("Alerts:") for alert in result["alerts"]: print(f" - {alert}") ``` ### Consumer App Comparison [Section titled “Consumer App Comparison”](#consumer-app-comparison) Compare app performance across competitors: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def compare_app_ratings(tickers): """Compare app ratings across competitors""" results = [] for symbol in tickers: try: df = fb.app_ratings.ticker(symbol, as_dataframe=True) if df.empty: continue ios = df["ios_score"].iloc[0] android = df["android_score"].iloc[0] combined = (ios + android) / 2 total_ratings = df["ios_ratingsCount"].iloc[0] + df["android_ratingsCount"].iloc[0] results.append({ "symbol": symbol, "ios": ios, "android": android, "combined": combined, "total_ratings": total_ratings }) except Exception: continue return sorted(results, key=lambda x: x["combined"], reverse=True) # Compare food delivery apps delivery_apps = ["UBER", "DASH", "GRUB"] comparison = compare_app_ratings(delivery_apps) print("Food Delivery App Comparison:") print("-" * 50) for app in comparison: print(f"{app['symbol']}: Combined {app['combined']:.2f} | iOS {app['ios']:.1f} | Android {app['android']:.1f}") ``` ### Rating Trend Analysis [Section titled “Rating Trend Analysis”](#rating-trend-analysis) Analyze rating trends over time: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def analyze_rating_trend(symbol, days=30): """Analyze rating trend over time""" df = fb.app_ratings.ticker(symbol, as_dataframe=True) if df.empty or len(df) < days: return None # Calculate combined rating for each row df["combined"] = (df["ios_score"] + df["android_score"]) / 2 recent = df["combined"].head(days) # Calculate trend: compare recent half vs older half second_half_avg = recent.head(days // 2).mean() first_half_avg = recent.tail(days // 2).mean() change = second_half_avg - first_half_avg if change > 0.05: trend = "improving" elif change < -0.05: trend = "declining" else: trend = "stable" return { "symbol": symbol, "current_rating": df["combined"].iloc[0], "30d_change": change, "trend": trend } result = analyze_rating_trend("NFLX", 30) print(f"{result['symbol']}: {result['trend']} (30d change: {result['30d_change']:+.2f})") ``` ### Platform Divergence Detection [Section titled “Platform Divergence Detection”](#platform-divergence-detection) Detect when iOS and Android ratings diverge: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def detect_platform_divergence(symbol, threshold=0.3): """Detect significant App Store vs Play Store rating divergence""" df = fb.app_ratings.ticker(symbol, as_dataframe=True) if df.empty: return None ios_score = df["ios_score"].iloc[0] android_score = df["android_score"].iloc[0] divergence = abs(ios_score - android_score) alert = None if divergence > threshold: better_platform = "App Store" if ios_score > android_score else "Play Store" worse_platform = "Play Store" if better_platform == "App Store" else "App Store" alert = f"{worse_platform} rating significantly lower than {better_platform}" return { "symbol": symbol, "ios_rating": ios_score, "android_rating": android_score, "divergence": divergence, "alert": alert } result = detect_platform_divergence("META") if result["alert"]: print(f"Alert: {result['alert']}") print(f" App Store: {result['ios_rating']:.1f} | Play Store: {result['android_rating']:.1f}") ``` ### App Portfolio Breakdown [Section titled “App Portfolio Breakdown”](#app-portfolio-breakdown) Find which product line is moving, rather than watching one blended number: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def portfolio_breakdown(symbol, min_observations=4): """Score change per app, so a decline can be attributed to a product""" apps = fb.app_ratings.ticker(symbol, as_dataframe=True, per_app=True) if apps.empty: return [] rows = [] for (platform, app_id, app_name), grp in apps.groupby( ["platform", "app_id", "app_name"], dropna=False ): grp = grp.sort_values("date") if len(grp) < min_observations: continue first, last = grp.iloc[0], grp.iloc[-1] rows.append({ "platform": platform, "app": app_name or f"app {app_id}", "score": last["score"], "score_change": last["score"] - first["score"], "ratings": last["ratings_count"], }) # Biggest apps first: a 0.3 drop on the flagship is not the same # event as a 0.3 drop on an app with 200 ratings. return sorted(rows, key=lambda r: r["ratings"] or 0, reverse=True) for app in portfolio_breakdown("AAPL")[:10]: print(f"{app['platform']:<8} {app['app']:<28} " f"{app['score']:.2f} ({app['score_change']:+.2f}) " f"{app['ratings']:,} ratings") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [App Ratings API Reference](/api-reference/app-ratings/) - Endpoint details, parameters, and response schema * [LinkedIn Metrics](/datasets/linkedin-data/) - Workforce and follower data * [News Sentiment](/datasets/sentiment/) - Market sentiment scores # Congressional Trading Dataset > Access US House and Senate stock trading data via REST API. Track congressional trades disclosed under the STOCK Act with 10+ years of history. Access stock trading activity from both chambers of the US Congress. Track purchases and sales disclosed by House Representatives and Senators under the STOCK Act, collected directly from the official disclosure systems and updated daily. ## What’s Included [Section titled “What’s Included”](#whats-included) The Congressional Trading dataset provides: * **Politician Name**: Name of the House or Senate member * **Chamber**: Whether the trade was filed by a House Representative or a Senator * **Transaction Type**: Purchase or Sale * **Amount Range**: Transaction size bracket, normalized to the statutory STOCK Act brackets — the string as originally filed is preserved in `amountRaw`, and rows whose amount could not be safely normalized are flagged via `amountFlag` * **Beneficial Owner**: Whose account traded (`owner`) — the member’s own (`SELF`), spouse (`SP`), dependent child (`DC`), or joint (`JT`) * **Transaction Date**: When the trade occurred * **Dual Dating**: Both the transaction date and the public disclosure date (`disclosureDate`) — the disclosure date marks when the trade became public, making it the correct point-in-time anchor for backtesting * **Historical Data**: 10+ years of history (filings since 2016), 100,000+ ticker-matched transactions ## Coverage [Section titled “Coverage”](#coverage) | Chamber | Source | Update Frequency | | ------- | ---------------------------------------------------------------- | ---------------- | | House | House Clerk financial disclosures (Periodic Transaction Reports) | Daily | | Senate | Senate eFD system (Periodic Transaction Reports) | Daily | Filings are collected directly from the official House and Senate disclosure systems — not resold third-party feeds — with the original filings archived for provenance. Coverage includes all 535 sitting members of both chambers, plus covered filings by former members, and spans US-listed stocks and ETFs with **10+ years of history (filings since 2016)** available for backtesting. **Disclosure timing:** the STOCK Act requires members of Congress to disclose trades within 45 days of the transaction. New filings appear in the dataset the day they are collected, but the reporting lag is inherent to the disclosure regime — factor it into any signal research. Members occasionally disclose trades late, so transaction dates older than the filing window do appear. Every trade carries both dates, so you can measure that lag directly rather than assuming it: `date` is when the member traded, `disclosureDate` is when the filing became public. Any backtest should enter on `disclosureDate` — entering on `date` assumes knowledge that was not available at the time and will overstate returns. Disclosure dates were backfilled across the full history, so nulls are rare — but the field is still nullable, so guard for missing values in point-in-time work. ## Beneficial Owner [Section titled “Beneficial Owner”](#beneficial-owner) Each trade identifies whose account traded via the `owner` field: | Value | Meaning | | ------------ | --------------------------------------------- | | `SELF` | The member’s own account | | `SP` | Spouse | | `DC` | Dependent child | | `JT` | Joint account | | Account code | A member-specific account identifier as filed | | `UNKNOWN` | Senate filing left the owner column blank | House filings that leave the owner column blank report `SELF`, per the House PTR-form instructions. This lets you separate trades a member made directly from spousal or family-account activity — a distinction that matters when weighting trades by how informed they are likely to be. ## Amount Ranges [Section titled “Amount Ranges”](#amount-ranges) Congressional disclosures report amounts in ranges: | Range | Minimum | Maximum | | ----------------------- | ---------- | ---------- | | $1,001 - $15,000 | $1,001 | $15,000 | | $15,001 - $50,000 | $15,001 | $50,000 | | $50,001 - $100,000 | $50,001 | $100,000 | | $100,001 - $250,000 | $100,001 | $250,000 | | $250,001 - $500,000 | $250,001 | $500,000 | | $500,001 - $1,000,000 | $500,001 | $1,000,000 | | $1,000,001 - $5,000,000 | $1,000,001 | $5,000,000 | | Over $5,000,000 | $5,000,001 | N/A | The `amount` field is normalized to these statutory brackets whenever the filed string is an unambiguous formatting variant of one; when a value is rewritten, the string as originally filed is preserved in `amountRaw`. Exact values (e.g., `"$360.00"`) and open-ended filing categories (e.g., `"Over $1,000,000"`) are kept as filed. A filing whose amount could not be read at all reports `amount` as `"Unknown"` with `amountFlag` set to `review`; a filing with two defensible readings is flagged `ambiguous` and kept as filed. Clean rows — the overwhelming majority — carry `null` in both fields. ## Quick Start [Section titled “Quick Start”](#quick-start) House and Senate trades are served by separate endpoints with an identical schema: * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") house_df = fb.house_trades.ticker("NVDA", as_dataframe=True) senate_df = fb.senate_trades.ticker("NVDA", as_dataframe=True) print(house_df) print(senate_df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" for chamber in ["house", "senate"]: response = requests.get( f"{BASE_URL}/congress/{chamber}/NVDA", headers={"Authorization": f"Bearer {API_KEY}"} ) data = response.json() for trade in data["data"]["trades"]: print(f"{trade['date']}: {trade['politician']} ({chamber}) - " f"{trade['transactionType']} {trade['amount']}") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/congressional-trading/). ## Visualization [Section titled “Visualization”](#visualization) Plot congressional trades on a price chart with the built-in SDK charts. You must supply your own price data: ```python from finbrain import FinBrainClient import yfinance as yf fb = FinBrainClient(api_key="YOUR_API_KEY") # Provide your own price data price_df = yf.download("NVDA", start="2024-01-01", end="2025-01-01") # One-line interactive charts with buy/sell markers on price fb.plot.house_trades("NVDA", price_df) fb.plot.senate_trades("NVDA", price_df) ``` ![House Trades Chart](/_astro/house-transactions-chart-python.Cv3NgWSt.png) NVDA House Representative trades overlaid on price chart ![Senate Trades Chart](/_astro/senate-transactions-chart-python.DqmJe7yA.png) NVDA Senate trades overlaid on price chart ## Use Cases [Section titled “Use Cases”](#use-cases) ### Congressional Trade Alert System [Section titled “Congressional Trade Alert System”](#congressional-trade-alert-system) Build alerts for significant congressional purchases across both chambers: ```python from finbrain import FinBrainClient import pandas as pd fb = FinBrainClient(api_key="YOUR_API_KEY") LARGE_TRADES = [ "$500,001 - $1,000,000", "$1,000,001 - $5,000,000", "Over $5,000,000" ] def get_congress_trades(symbol): """Combine House and Senate trades for a symbol""" frames = [] for chamber, api in [("house", fb.house_trades), ("senate", fb.senate_trades)]: try: df = api.ticker(symbol, as_dataframe=True) df["chamber"] = chamber frames.append(df) except Exception: continue return pd.concat(frames) if frames else pd.DataFrame() def scan_large_congressional_trades(symbols): """Find stocks with large congressional purchases""" results = [] for symbol in symbols: df = get_congress_trades(symbol) if df.empty: continue large_purchases = df[ (df["transactionType"] == "Purchase") & (df["amount"].isin(LARGE_TRADES)) ] if not large_purchases.empty: results.append({ "symbol": symbol, "trades": large_purchases }) return results # Scan popular stocks symbols = ["NVDA", "AAPL", "MSFT", "GOOGL", "AMZN", "META", "TSLA"] alerts = scan_large_congressional_trades(symbols) for alert in alerts: print(f"\n{alert['symbol']}:") for _, trade in alert['trades'].iterrows(): print(f" {trade['politician']} ({trade['chamber']}): {trade['amount']}") ``` ### Follow Specific Politicians [Section titled “Follow Specific Politicians”](#follow-specific-politicians) Track trading activity of specific members of Congress: ```python from finbrain import FinBrainClient import pandas as pd fb = FinBrainClient(api_key="YOUR_API_KEY") def get_politician_trades(politician_name, symbols): """Get all trades by a specific member across both chambers""" all_trades = [] for symbol in symbols: for api in [fb.house_trades, fb.senate_trades]: try: df = api.ticker(symbol, as_dataframe=True) mask = df["politician"].str.lower().str.contains(politician_name.lower()) matched = df[mask].copy() matched["symbol"] = symbol all_trades.append(matched) except Exception: continue return pd.concat(all_trades) if all_trades else pd.DataFrame() # Track a specific politician's trades trades = get_politician_trades( "Pelosi", ["NVDA", "AAPL", "MSFT", "GOOGL", "AMZN", "CRM", "RBLX"] ) for date, row in trades.iterrows(): print(f"{date}: {row['symbol']} - {row['transactionType']} {row['amount']}") ``` ### Cluster Buying Signal [Section titled “Cluster Buying Signal”](#cluster-buying-signal) Find stocks where multiple members of Congress are buying: ```python from finbrain import FinBrainClient import pandas as pd fb = FinBrainClient(api_key="YOUR_API_KEY") def find_cluster_buying(symbol, min_buyers=3): """Find if multiple members of Congress are buying a stock""" frames = [] for api in [fb.house_trades, fb.senate_trades]: try: frames.append(api.ticker(symbol, as_dataframe=True)) except Exception: continue if not frames: return None df = pd.concat(frames) purchases = df[df["transactionType"] == "Purchase"] # Count unique members making purchases buyers = purchases["politician"].unique() if len(buyers) >= min_buyers: return { "symbol": symbol, "unique_buyers": len(buyers), "total_purchases": len(purchases), "politicians": list(buyers) } return None # Check multiple symbols for symbol in ["NVDA", "AAPL", "MSFT", "GOOGL", "META"]: result = find_cluster_buying(symbol) if result: print(f"{symbol}: {result['unique_buyers']} unique buyers") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Congressional Trading API Reference](/api-reference/congressional-trading/) - Endpoint details, parameters, and response schema * [Insider Transactions](/datasets/insider-transactions/) - Corporate insider trades * [Corporate Lobbying](/datasets/corporate-lobbying/) - Lobbying disclosure filings # Corporate Lobbying Dataset > Access corporate lobbying filings via REST API. Track lobbying expenditures, registrant firms, issue codes, and government entities from US Senate LDA disclosures. Track corporate lobbying activity from US Senate Lobbying Disclosure Act (LDA) filings. See which companies spend on lobbying, which firms represent them, what policy issues they target, and which government entities they engage. ## What’s Included [Section titled “What’s Included”](#whats-included) The Corporate Lobbying dataset provides: * **Filing Details**: Public posting date, filing year, quarter, and unique filing identifier * **Registrant Information**: Lobbying firm name and client company * **Financial Data**: Income and expenses reported per filing * **Issue Codes**: Policy areas lobbied on (e.g., TAX, TRD, COM) * **Government Entities**: Bodies engaged (e.g., Senate, House) ## Coverage [Section titled “Coverage”](#coverage) | Source | Description | Update Frequency | | ------------- | ------------------------------- | ---------------- | | US Senate LDA | Lobbying Disclosure Act filings | Quarterly | Corporate lobbying data has **15+ years of historical filings** available for long-horizon backtesting and historical analysis. **Point-in-time semantics:** a quarter’s lobbying activity is not public until its LDA report is filed, so each record’s `date` — the public posting date of the filing — is the correct look-ahead-free anchor for backtests. The reporting period itself is carried separately in `filingYear` and `quarter`. Filings are published roughly 30 days after quarter-end (a property of the quarterly disclosure regime, not a collection delay), so a quarter’s activity typically becomes available around the end of January, April, July, and October. ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.corporate_lobbying.ticker("AAPL", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" response = requests.get( f"{BASE_URL}/lobbying/AAPL", headers={"Authorization": f"Bearer {API_KEY}"} ) data = response.json() for filing in data["data"]["filings"]: print(f"{filing['date']} Q{filing['quarter']}: {filing['registrantName']} " f"- ${filing['income']:,.0f} income, ${filing['expenses']:,.0f} expenses") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/corporate-lobbying/). ## Key Fields [Section titled “Key Fields”](#key-fields) | Field | Description | Example | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | | `clientName` | Company being represented | Apple Inc. | | `registrantName` | Lobbying firm hired | Lobbying Firm LLC | | `income` | Income reported by registrant (USD) | 50000 | | `expenses` | Expenses reported by registrant (USD) | 75000 | | `issueCodes` | Policy areas lobbied on | \[“TAX”, “TRD”, “COM”] | | `governmentEntities` | Government bodies engaged | \[“Senate”, “House”] | | `quarter` | Filing quarter | Q3 | | `filingYear` | Filing year | 2025 | | `cik` | SEC Central Index Key of the company as of this record (10-digit zero-padded, `null` when unresolved) — for joining to your own SEC-keyed data; not queryable as a parameter | `0000320193` | ## Common Issue Codes [Section titled “Common Issue Codes”](#common-issue-codes) | Code | Policy Area | | ---- | --------------------------------------------- | | TAX | Taxation/Internal Revenue Code | | TRD | Trade (Domestic and Foreign) | | COM | Communications/Broadcasting/Radio/TV | | CPT | Computer Industry | | ENV | Environmental/Superfund | | HCR | Health Issues | | DEF | Defense | | FIN | Financial Institutions/Investments/Securities | | IMM | Immigration | | TEC | Telecommunications | ## Use Cases [Section titled “Use Cases”](#use-cases) ### Top Lobbying Spenders [Section titled “Top Lobbying Spenders”](#top-lobbying-spenders) Scan a list of tickers to find companies with the highest lobbying spend: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def scan_lobbying_spend(symbols): """Find companies with the highest lobbying spend""" results = [] for symbol in symbols: try: df = fb.corporate_lobbying.ticker(symbol, as_dataframe=True) total_spend = df["income"].sum() + df["expenses"].sum() results.append({ "symbol": symbol, "filings": len(df), "total_spend": total_spend }) except Exception: continue return sorted(results, key=lambda x: x["total_spend"], reverse=True) tech_symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "META"] spenders = scan_lobbying_spend(tech_symbols) for s in spenders: print(f"{s['symbol']}: {s['filings']} filings, ${s['total_spend']:,.0f} total spend") ``` ### Quarterly Spend Trend [Section titled “Quarterly Spend Trend”](#quarterly-spend-trend) Track how a company’s lobbying spend changes quarter over quarter: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def quarterly_lobbying_trend(symbol): """Analyze lobbying spend by quarter""" df = fb.corporate_lobbying.ticker(symbol, as_dataframe=True) df["period"] = df["filingYear"].astype(str) + "-" + df["quarter"] df["total_spend"] = df["income"] + df["expenses"] quarterly = df.groupby("period").agg( filings=("total_spend", "count"), total_spend=("total_spend", "sum"), registrants=("registrantName", "nunique") ).sort_index() return quarterly trend = quarterly_lobbying_trend("AAPL") for period, row in trend.iterrows(): print(f"{period}: ${row['total_spend']:,.0f} across {row['registrants']} firms " f"({row['filings']} filings)") ``` ### Issue Code Analysis [Section titled “Issue Code Analysis”](#issue-code-analysis) Discover which policy areas a company focuses its lobbying efforts on: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def analyze_issue_codes(symbol): """Break down lobbying by policy area""" df = fb.corporate_lobbying.ticker(symbol, as_dataframe=True) # Explode issueCodes list into individual rows exploded = df.explode("issueCodes") issue_counts = exploded.groupby("issueCodes").agg( filings=("issueCodes", "count"), total_income=("income", "sum") ).sort_values("filings", ascending=False) return issue_counts issues = analyze_issue_codes("AAPL") for code, row in issues.iterrows(): print(f"{code}: {row['filings']} filings, ${row['total_income']:,.0f} income") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Corporate Lobbying API Reference](/api-reference/corporate-lobbying/) - Endpoint details, parameters, and response schema * [Insider Transactions Dataset](/datasets/insider-transactions/) - Track executive trades * [Congressional Trading Dataset](/datasets/congressional-trading/) - US House and Senate trading activity # Government Contracts Dataset > Access federal government contract awards via REST API. Track contract values, awarding agencies, NAICS codes, and recipient companies from USAspending.gov data mapped to stock tickers. Python SDK included. Track federal government contract awards sourced from USAspending.gov and mapped to public company tickers. See which companies win government contracts, the awarding agencies, contract values, industry classifications, and contract periods. ## What’s Included [Section titled “What’s Included”](#whats-included) The Government Contracts dataset provides: * **Award Details**: Award ID and total award value * **Agency Information**: Awarding agency and sub-agency * **Recipient Data**: Recipient company name mapped to stock ticker * **Contract Period**: Start and end dates for each award * **Industry Classification**: NAICS codes and descriptions * **Contract Description**: Plain-text description of the contract scope ## Coverage [Section titled “Coverage”](#coverage) | Source | Description | Update Frequency | | --------------- | ----------------------------------------------- | ---------------- | | USAspending.gov | Federal contract awards mapped to stock tickers | Daily | Government contracts data has **10+ years of historical awards, back to 2016** available for backtesting. ## Using the Data Point-in-Time [Section titled “Using the Data Point-in-Time”](#using-the-data-point-in-time) The period-of-performance `startDate` is a fixed, clean timing anchor for event studies and backtests. Award records are deduplicated by federal award ID and updated as contracts evolve, so `awardAmount` and `endDate` reflect the latest reported state of each award rather than a historical snapshot. For strictly look-ahead-free work, anchor on `startDate` and treat the award amount as a current-state field. Note: `awardType` and `contractAwardType` are present in the schema but are not populated by the source award endpoint — use `naicsDescription` for sector and category classification. ## FinBrain Terminal [Section titled “FinBrain Terminal”](#finbrain-terminal) Browse government contracts for any ticker directly in the FinBrain Terminal — with summary stats, filtering, and contract details at a glance. ![LMT Government Contracts in FinBrain Terminal](/_astro/lmt-government-contracts.bCNiEcLE.png) Government contracts for Lockheed Martin (LMT) in the FinBrain Terminal Use the Government Contracts screener to scan recent contract awards across all tickers, with filtering by company, agency, industry, and award amount. ![Government Contracts Screener](/_astro/government-contracts-screener.C5XnhLz-.png) Government Contracts screener showing recent federal contract awards ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.government_contracts.ticker("LMT", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" response = requests.get( f"{BASE_URL}/government-contracts/LMT", headers={"Authorization": f"Bearer {API_KEY}"} ) data = response.json() for contract in data["data"]["contracts"]: print(f"{contract['startDate']}: ${contract['awardAmount']:,.0f} " f"from {contract['awardingAgency']} — {contract['description']}") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/government-contracts/). ## Key Fields [Section titled “Key Fields”](#key-fields) | Field | Description | Example | | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | | `awardId` | Unique federal award identifier (dedup key) | CONT\_AWD\_0001 | | `awardAmount` | Total award value in USD (latest reported state) | 50000000 | | `awardingAgency` | Federal agency issuing the contract | Department of Defense | | `awardingSubAgency` | Sub-agency within the awarding agency | Department of the Army | | `recipientName` | Company receiving the contract | Lockheed Martin Corporation | | `startDate` | Period-of-performance start (YYYY-MM-DD) — the point-in-time anchor | 2025-06-01 | | `endDate` | Period-of-performance end (YYYY-MM-DD) | 2026-06-01 | | `description` | Plain-text description of the contract | Aircraft maintenance services | | `naicsCode` | NAICS industry classification code | 336411 | | `naicsDescription` | Human-readable NAICS description | Aircraft Manufacturing | | `awardType`, `contractAwardType` | Present in the schema but not populated by the source award endpoint — use `naicsDescription` for classification | (empty) | | `cik` | SEC Central Index Key of the company as of this record (10-digit zero-padded, `null` when unresolved) — for joining to your own SEC-keyed data; not queryable as a parameter | `0000936468` | ## Use Cases [Section titled “Use Cases”](#use-cases) ### Top Contract Recipients [Section titled “Top Contract Recipients”](#top-contract-recipients) Scan defense tickers to find companies with the highest total contract value: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def scan_contract_value(symbols): """Find companies with the highest government contract value""" results = [] for symbol in symbols: try: df = fb.government_contracts.ticker(symbol, as_dataframe=True) total_value = df["awardAmount"].sum() results.append({ "symbol": symbol, "contracts": len(df), "total_value": total_value }) except Exception: continue return sorted(results, key=lambda x: x["total_value"], reverse=True) defense_symbols = ["LMT", "RTX", "GD", "NOC", "BA"] recipients = scan_contract_value(defense_symbols) for r in recipients: print(f"{r['symbol']}: {r['contracts']} contracts, ${r['total_value']:,.0f} total value") ``` ### Agency Breakdown [Section titled “Agency Breakdown”](#agency-breakdown) Analyze which federal agencies award contracts to a given company: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def agency_breakdown(symbol): """Break down contracts by awarding agency""" df = fb.government_contracts.ticker(symbol, as_dataframe=True) by_agency = df.groupby("awardingAgency").agg( contracts=("awardAmount", "count"), total_value=("awardAmount", "sum") ).sort_values("total_value", ascending=False) return by_agency agencies = agency_breakdown("LMT") for agency, row in agencies.iterrows(): print(f"{agency}: {row['contracts']} contracts, ${row['total_value']:,.0f}") ``` ### Contract Size Analysis [Section titled “Contract Size Analysis”](#contract-size-analysis) Categorize contracts by size to understand the award distribution: ```python import pandas as pd from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def contract_size_distribution(symbol): """Categorize contracts by size buckets""" df = fb.government_contracts.ticker(symbol, as_dataframe=True) bins = [0, 1_000_000, 10_000_000, 100_000_000, float("inf")] labels = ["Under $1M", "$1M–$10M", "$10M–$100M", "$100M+"] df["size_bucket"] = pd.cut(df["awardAmount"], bins=bins, labels=labels) distribution = df.groupby("size_bucket", observed=True).agg( contracts=("awardAmount", "count"), total_value=("awardAmount", "sum") ) return distribution dist = contract_size_distribution("RTX") for bucket, row in dist.iterrows(): print(f"{bucket}: {row['contracts']} contracts, ${row['total_value']:,.0f}") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Government Contracts API Reference](/api-reference/government-contracts/) - Endpoint details, parameters, and response schema * [Corporate Lobbying Dataset](/datasets/corporate-lobbying/) - Track corporate lobbying activity * [Insider Transactions Dataset](/datasets/insider-transactions/) - Track executive trades * [Congressional Trading Dataset](/datasets/congressional-trading/) - US House and Senate trading activity # Insider Transactions Dataset > Access daily insider trading data via REST API. Track executive purchases, sales, and option exercises from SEC Form 4 filings. Track executive purchases, sales, option exercises, and ownership changes from SEC Form 4 filings. Insider transactions are among the most closely watched public disclosure signals in systematic research. ## What’s Included [Section titled “What’s Included”](#whats-included) The Insider Transactions dataset provides: * **Transaction Details**: Buy, sell, option exercise, and gift transactions * **Insider Information**: Name, title, and relationship to company * **Share Data**: Number of shares and price per share * **Ownership Changes**: Post-transaction holdings * **Dual Dating**: Both the transaction date and the SEC filing date (`filingDate`) — the filing date marks when the trade became public, making it the correct point-in-time anchor for backtesting * **Per-Row Provenance**: Every transaction carries `filingUrl`, a direct link to the source Form 4 on SEC EDGAR — any record can be audited against the official filing in one click * **SEC Entity Key**: Each row carries `cik`, the issuer’s SEC Central Index Key as of that record (10-digit zero-padded string, `null` when unresolved), for joining to your own SEC-keyed data — it is a returned field, not a query parameter ## Coverage [Section titled “Coverage”](#coverage) | Filing Type | Description | Update Frequency | | ----------- | ------------------------------- | ---------------- | | Form 4 | Changes in beneficial ownership | Daily | New Form 4 filings are collected from SEC EDGAR every business day, so a filed transaction is typically available via the API within one business day of publication. SEC rules require insiders to file within 2 business days of the trade, making this one of the timeliest public disclosure signals available. Insider transaction data has **10+ years of historical filings, back to 2015** available for backtesting. ## Transaction Types & Signals [Section titled “Transaction Types & Signals”](#transaction-types--signals) | Type | Description | Signal | | -------------------- | --------------------------------- | ---------------------------------------------- | | Purchase | Open market buy | Bullish — insiders buying with their own money | | Sale | Open market sell | May be neutral (planned sales) or bearish | | Derivative\_Purchase | Derivative security buy | Bullish — leveraged insider conviction | | Derivative\_Sale | Derivative security sell | Bearish or hedging activity | | Exercise | Option/warrant exercise | Neutral — compensation related | | Award | Grant/award from company | Neutral — compensation event | | Gift | Shares donated | Neutral — estate/tax planning | | Tax | Tax withholding on vesting | Neutral — automatic withholding | | Conversion | Security conversion (NASDAQ only) | Neutral — structural change | | Other\_Acquisition | Other share acquisition | Context-dependent | | Other\_Disposition | Other share disposition | Context-dependent | For analysis, these types can be grouped into three categories: * **Acquisitions** (net share increase): Purchase, Derivative\_Purchase, Exercise, Award, Other\_Acquisition * **Dispositions** (net share decrease): Sale, Derivative\_Sale, Tax, Gift, Other\_Disposition * **Neutral** (no net change): Conversion ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.insider_transactions.ticker("AAPL", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" response = requests.get( f"{BASE_URL}/insider-trading/AAPL", headers={"Authorization": f"Bearer {API_KEY}"} ) data = response.json() for txn in data["data"]["transactions"]: print(f"{txn['date']}: {txn['insider']} - {txn['transactionType']} ${txn['totalValue']:,.0f}") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/insider-transactions/). ## Visualization [Section titled “Visualization”](#visualization) Plot insider transactions on a price chart with the built-in SDK chart. You must supply your own price data: ```python from finbrain import FinBrainClient import yfinance as yf fb = FinBrainClient(api_key="YOUR_API_KEY") # Provide your own price data price_df = yf.download("NVDA", start="2024-01-01", end="2025-01-01") # One-line interactive chart with buy/sell markers on price fb.plot.insider_transactions("NVDA", price_df) ``` ![Insider Transactions Chart](/_astro/insider-transactions-chart-python.Co5pme8T.png) NVDA insider transactions overlaid on price chart ## Use Cases [Section titled “Use Cases”](#use-cases) ### Insider Purchase Scanner [Section titled “Insider Purchase Scanner”](#insider-purchase-scanner) Build a scanner to find stocks with significant insider buying: ```python from finbrain import FinBrainClient from datetime import datetime, timedelta fb = FinBrainClient(api_key="YOUR_API_KEY") def scan_insider_purchases(symbols, days=30, min_value=100000): """Find symbols with significant insider purchases""" date_from = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d") date_to = datetime.now().strftime("%Y-%m-%d") results = [] for symbol in symbols: try: df = fb.insider_transactions.ticker( symbol, date_from=date_from, date_to=date_to, as_dataframe=True ) purchases = df[ (df["transactionType"] == "Purchase") & (df["totalValue"] >= min_value) ] if not purchases.empty: total_value = purchases["totalValue"].sum() results.append({ "symbol": symbol, "purchases": len(purchases), "total_value": total_value }) except Exception: continue return sorted(results, key=lambda x: x["total_value"], reverse=True) # Scan tech stocks tech_symbols = ["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA"] purchases = scan_insider_purchases(tech_symbols) for p in purchases: print(f"{p['symbol']}: {p['purchases']} purchases, ${p['total_value']:,.0f}") ``` ### Cluster Buying Detection [Section titled “Cluster Buying Detection”](#cluster-buying-detection) Detect when multiple insiders are buying - a stronger bullish signal: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def detect_cluster_buying(symbol): """Detect cluster buying (multiple insiders buying)""" df = fb.insider_transactions.ticker(symbol, as_dataframe=True) purchases = df[df["transactionType"] == "Purchase"].copy() # Group by month purchases["month"] = purchases.index.to_series().str[:7] # YYYY-MM clusters = [] for month, group in purchases.groupby("month"): unique_insiders = group["insider"].unique() if len(unique_insiders) >= 2: clusters.append({ "period": month, "insiders": list(unique_insiders), "total_value": group["totalValue"].sum() }) return clusters clusters = detect_cluster_buying("AAPL") for c in clusters: print(f"{c['period']}: {len(c['insiders'])} insiders, ${c['total_value']:,.0f}") ``` ### C-Suite Tracking [Section titled “C-Suite Tracking”](#c-suite-tracking) Focus on CEO, CFO, and board member transactions - often the most informed insiders: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") C_SUITE_TITLES = [ "Chief Executive Officer", "CEO", "Chief Financial Officer", "CFO", "Chief Operating Officer", "COO", "President", "Director", "Chairman" ] def get_csuite_transactions(symbol): """Filter for C-suite and board member transactions""" df = fb.insider_transactions.ticker(symbol, as_dataframe=True) mask = df["relationship"].str.lower().apply( lambda r: any(title.lower() in r for title in C_SUITE_TITLES) ) return df[mask] csuite = get_csuite_transactions("AAPL") for date, row in csuite.iterrows(): print(f"{date}: {row['insider']} ({row['relationship']})") print(f" {row['transactionType']} ${row['totalValue']:,.0f}") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Insider Transactions API Reference](/api-reference/insider-transactions/) - Endpoint details, parameters, and response schema * [Congressional Trading Data](/datasets/congressional-trading/) - Track politician trades on the same ticker keys — corporate insiders and members of Congress trading the same names is a natural cross-reference # LinkedIn Metrics Dataset > Access LinkedIn employee and follower data via REST API. Track workforce growth and company popularity as alternative data signals. Access LinkedIn employee counts and follower metrics as alternative data signals. Track workforce growth and company popularity trends that may precede stock price movements. ## What’s Included [Section titled “What’s Included”](#whats-included) The LinkedIn Metrics dataset provides: * **Employee Count**: Current number of employees on LinkedIn * **Employee Growth**: Month-over-month and year-over-year changes * **Follower Count**: Company page followers * **Follower Growth**: Trending popularity metrics * **Job Count**: Open job listings (when available) * **Historical Data**: Track workforce trends over time * **Weekly Updates**: Fresh data every week ## Coverage [Section titled “Coverage”](#coverage) | Coverage | Details | | ---------------- | ---------------------------------------- | | Markets | S\&P 500, NASDAQ, NYSE | | Metrics | Employees, followers, jobs, growth rates | | Update Frequency | Weekly | | Historical Data | 2+ years | ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.linkedin_data.ticker("META", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get(f"{BASE_URL}/v2/linkedin/META", headers=headers) result = response.json() # Access LinkedIn data from the response envelope for entry in result["data"][:5]: print(f"{entry['date']}: {entry['employeeCount']} employees | {entry['followerCount']} followers") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/linkedin-data/). ## Visualization [Section titled “Visualization”](#visualization) Plot LinkedIn metrics with the built-in SDK chart: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # One-line interactive chart (employee bars + follower line) fb.plot.linkedin("AAPL") ``` ![LinkedIn Metrics Chart](/_astro/linkedin-metrics-chart-python.CnqN3Sso.png) AAPL LinkedIn employee and follower trends over time ## Interpreting LinkedIn Metrics [Section titled “Interpreting LinkedIn Metrics”](#interpreting-linkedin-metrics) ### Employee Growth Signals [Section titled “Employee Growth Signals”](#employee-growth-signals) | YoY Growth | Interpretation | Signal | | ---------- | ------------------- | ------------------- | | > 20% | Rapid expansion | Strong growth phase | | 10% - 20% | Healthy growth | Positive outlook | | 0% - 10% | Moderate growth | Stable operations | | -10% - 0% | Slight contraction | Caution | | < -10% | Significant layoffs | Potential distress | ### Follower Growth Signals [Section titled “Follower Growth Signals”](#follower-growth-signals) | MoM Growth | Interpretation | | ---------- | ------------------------- | | > 3% | Viral growth / major news | | 1% - 3% | Above average interest | | 0% - 1% | Normal growth | | < 0% | Declining interest | ## Use Cases [Section titled “Use Cases”](#use-cases) ### Workforce Trend Scanner [Section titled “Workforce Trend Scanner”](#workforce-trend-scanner) Scan for companies with significant workforce changes: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def scan_workforce_changes(tickers): """Find companies with significant workforce changes""" results = [] for symbol in tickers: try: df = fb.linkedin_data.ticker(symbol, as_dataframe=True) if df.empty or len(df) < 30: continue # Compare current to 30 days ago latest_employees = df["employeeCount"].iloc[0] older_employees = df["employeeCount"].iloc[29] change = ((latest_employees - older_employees) / older_employees) * 100 results.append({ "symbol": symbol, "employees": latest_employees, "change_30d": change }) except Exception: continue # Sort by change return sorted(results, key=lambda x: x["change_30d"], reverse=True) tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "NFLX"] changes = scan_workforce_changes(tickers) print("Workforce Changes (30-day):") for c in changes: trend = "hiring" if c["change_30d"] > 0 else "declining" print(f" {c['symbol']}: {c['employees']:,} employees ({c['change_30d']:+.1f}% - {trend})") ``` ### Growth Momentum Indicator [Section titled “Growth Momentum Indicator”](#growth-momentum-indicator) Create a composite growth score: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def calculate_growth_momentum(symbol): """Calculate growth momentum from LinkedIn data""" df = fb.linkedin_data.ticker(symbol, as_dataframe=True) if df.empty or len(df) < 7: return None # Calculate weekly growth rates emp_growth = ((df["employeeCount"].iloc[0] - df["employeeCount"].iloc[6]) / df["employeeCount"].iloc[6]) * 100 fol_growth = ((df["followerCount"].iloc[0] - df["followerCount"].iloc[6]) / df["followerCount"].iloc[6]) * 100 # Weighted composite score momentum = emp_growth * 0.6 + fol_growth * 0.4 return { "symbol": symbol, "momentum_score": momentum, "employee_growth": emp_growth, "follower_growth": fol_growth, "signal": "bullish" if momentum > 1 else "bearish" if momentum < -1 else "neutral" } momentum = calculate_growth_momentum("NVDA") print(f"{momentum['symbol']}: {momentum['signal']} (Score: {momentum['momentum_score']:.2f})") ``` ### Tech Sector Comparison [Section titled “Tech Sector Comparison”](#tech-sector-comparison) Compare workforce trends across tech sector: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def compare_tech_workforce(): """Compare workforce metrics across major tech companies""" tech_tickers = { "AAPL": "Apple", "MSFT": "Microsoft", "GOOGL": "Alphabet", "AMZN": "Amazon", "META": "Meta", "NVDA": "NVIDIA", "TSLA": "Tesla" } results = [] for symbol, name in tech_tickers.items(): try: df = fb.linkedin_data.ticker(symbol, as_dataframe=True) if df.empty: continue results.append({ "company": name, "symbol": symbol, "employees": df["employeeCount"].iloc[0], "followers": df["followerCount"].iloc[0] }) except Exception: continue # Sort by employee count return sorted(results, key=lambda x: x["employees"], reverse=True) comparison = compare_tech_workforce() print("Tech Workforce Comparison:") print("-" * 60) for c in comparison: print(f"{c['company']:12} | {c['employees']:>10,} employees | {c['followers']:>12,} followers") ``` ### Detect Hiring Acceleration [Section titled “Detect Hiring Acceleration”](#detect-hiring-acceleration) Find companies that are accelerating hiring: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def detect_hiring_acceleration(symbol, lookback_days=30): """Detect if a company is accelerating hiring""" df = fb.linkedin_data.ticker(symbol, as_dataframe=True) if df.empty or len(df) < lookback_days: return None # Calculate growth rate for recent period vs older period emp = df["employeeCount"] recent_start = emp.iloc[0] recent_end = emp.iloc[lookback_days // 2 - 1] older_start = emp.iloc[lookback_days // 2] older_end = emp.iloc[lookback_days - 1] recent_growth = ((recent_start - recent_end) / recent_end) * 100 older_growth = ((older_start - older_end) / older_end) * 100 acceleration = recent_growth - older_growth return { "symbol": symbol, "recent_growth": recent_growth, "older_growth": older_growth, "acceleration": acceleration, "signal": "accelerating" if acceleration > 0.5 else "decelerating" if acceleration < -0.5 else "stable" } result = detect_hiring_acceleration("NVDA") print(f"Hiring trend: {result['signal']} (Acceleration: {result['acceleration']:.2f}%)") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [LinkedIn Data API Reference](/api-reference/linkedin-data/) - Endpoint details, parameters, and response schema * [App Ratings](/datasets/app-ratings/) - Consumer app data * [Insider Transactions](/datasets/insider-transactions/) - Track executive trades # News Dataset > Access real-time financial news with AI sentiment scores via REST API. Track headlines, sources, and market sentiment for any stock ticker. Access real-time financial news articles with AI-powered sentiment analysis for any stock ticker. FinBrain’s news dataset aggregates headlines from major financial publications and scores each article for market sentiment, giving you a comprehensive view of the news landscape around your positions. ## What’s Included [Section titled “What’s Included”](#whats-included) The News dataset provides: * **News Article Headlines**: Full headline text for each article with publication dates * **Source Attribution**: Publication name for every article * **Direct Article URLs**: Links to the original source article * **AI Sentiment Scores**: Normalized score from -1 (bearish) to +1 (bullish), nullable when unavailable * **Coverage**: US-listed stocks and ETFs, with partial coverage of selected international markets ## Coverage [Section titled “Coverage”](#coverage) | Detail | Description | | ---------------- | ------------------------------------------------------------ | | Markets | US equities & ETFs (primary); partial international coverage | | Update Frequency | Real-time / multiple times daily | | History | Rolling recent articles | | API Endpoint | `/v2/news/{symbol}` | ## Understanding News Sentiment [Section titled “Understanding News Sentiment”](#understanding-news-sentiment) | Score Range | Interpretation | Signal | | ------------ | ----------------- | ----------------- | | Above 0.5 | Strongly positive | Bullish sentiment | | 0.1 to 0.5 | Mildly positive | Slightly bullish | | -0.1 to 0.1 | Neutral | No strong signal | | -0.5 to -0.1 | Mildly negative | Slightly bearish | | Below -0.5 | Strongly negative | Bearish sentiment | **Note:** The `sentiment` field can be `null` when no score is available for an article. Always handle this case in your code. ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("AAPL", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" headers = {"Authorization": f"Bearer {API_KEY}"} # Get news for AAPL response = requests.get(f"{BASE_URL}/news/AAPL", headers=headers) result = response.json() for article in result["data"]["articles"]: sentiment = article["sentiment"] or "N/A" print(f"{article['date']} | {article['source']} | {sentiment} | {article['headline']}") ``` For complete endpoint details, parameters, and response schema, see the [News API Reference](/api-reference/news/). ## Use Cases [Section titled “Use Cases”](#use-cases) ### Filter High-Sentiment News Articles [Section titled “Filter High-Sentiment News Articles”](#filter-high-sentiment-news-articles) Surface only the most positive or negative news articles for a ticker: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("TSLA", as_dataframe=True) # Filter articles with strong sentiment bullish_news = df[df["sentiment"].notna() & (df["sentiment"] > 0.5)] bearish_news = df[df["sentiment"].notna() & (df["sentiment"] < -0.5)] print(f"Strongly bullish articles: {len(bullish_news)}") for _, a in bullish_news.iterrows(): print(f" [{a['sentiment']:.2f}] {a['headline']}") print(f"\nStrongly bearish articles: {len(bearish_news)}") for _, a in bearish_news.iterrows(): print(f" [{a['sentiment']:.2f}] {a['headline']}") ``` ### Aggregate Daily Sentiment from News [Section titled “Aggregate Daily Sentiment from News”](#aggregate-daily-sentiment-from-news) Compute an average sentiment score per day from individual article scores: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("NVDA", as_dataframe=True) # Filter out articles without sentiment scores scored = df[df["sentiment"].notna()].copy() # Group by date and compute daily average daily_avg = scored.groupby(scored.index).agg( avg_sentiment=("sentiment", "mean"), article_count=("sentiment", "count") ) for date, row in daily_avg.sort_index().iterrows(): print(f"{date}: avg sentiment = {row['avg_sentiment']:.3f} ({int(row['article_count'])} articles)") ``` ### Track News Volume and Sentiment Trend [Section titled “Track News Volume and Sentiment Trend”](#track-news-volume-and-sentiment-trend) Monitor how news volume and sentiment shift over time for early signals: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.news.ticker("AMZN", as_dataframe=True) # Compute daily volume and average sentiment daily = df.groupby(df.index).agg( count=("headline", "count"), avg_sentiment=("sentiment", "mean") ) for date, row in daily.sort_index().iterrows(): sent_str = f"{row['avg_sentiment']:.3f}" if row["avg_sentiment"] == row["avg_sentiment"] else "N/A" print(f"{date}: {int(row['count'])} articles, avg sentiment: {sent_str}") ``` Note News article URLs may occasionally be relative paths. Prepend the source base URL if a URL starts with `/`. ## Related Resources [Section titled “Related Resources”](#related-resources) * [News API Reference](/api-reference/news/) - Endpoint details, parameters, and response schema * [News Sentiment Dataset](/datasets/sentiment/) - Aggregated daily sentiment scores * [Screener API Reference](/api-reference/screener/) - Screen tickers by sentiment and other criteria # Datasets Overview > FinBrain delivers 12 alternative datasets covering disclosure filings, social and consumer signals, and market and trading data — all normalized, ticker-mapped, and accessible via Terminal, API, SDK, and MCP. FinBrain provides 12 alternative datasets focused on US-listed stocks and ETFs, normalized and ticker-mapped for direct integration into research pipelines, trading systems, and visual analysis. Each dataset is documented on its own page with sample responses, code examples, and use cases. ## Coverage [Section titled “Coverage”](#coverage) | Metric | Value | | ----------------------- | ---------------------------------------- | | US stocks & ETFs | 12,000+ (NYSE and NASDAQ) | | Datasets | 12 | | Historical depth | 10 years on average (varies by dataset) | | Price forecast coverage | 28,000+ tickers across 20 global markets | The alternative datasets cover US-listed assets. [Price Forecasts](/datasets/ai-forecasts/) additionally span 20 global markets, including international equities, forex, crypto, and commodities. ## Dataset Categories [Section titled “Dataset Categories”](#dataset-categories) We organize the dataset catalog into three categories based on the type of signal they provide. ### Government & Regulatory [Section titled “Government & Regulatory”](#government--regulatory) Public disclosure data tied to government processes — congressional trading, lobbying activity, and federal contract awards. These datasets are difficult and time-consuming to aggregate independently and provide signals not found in price data alone. | Dataset | Description | Update Frequency | | --------------------------------------------------------- | ------------------------------------------------------------------ | ---------------- | | [Congressional Trading](/datasets/congressional-trading/) | US House and Senate member trading activity from STOCK Act filings | As filed | | [Corporate Lobbying](/datasets/corporate-lobbying/) | Federal LDA filings tracking corporate influence | Quarterly | | [Government Contracts](/datasets/government-contracts/) | Federal contract awards mapped to ticker symbols | Daily | | [Patent Filings](/datasets/patent-filings/) | USPTO granted patents mapped to ticker symbols | Weekly | ### Social & Consumer Intelligence [Section titled “Social & Consumer Intelligence”](#social--consumer-intelligence) Signals from public social platforms, news media, professional networks, and app ecosystems. Useful for monitoring narrative shifts, retail attention, and consumer-facing company performance. | Dataset | Description | Update Frequency | | --------------------------------------------- | ------------------------------------------------- | ---------------- | | [News Sentiment](/datasets/sentiment/) | AI-generated sentiment scores from financial news | Daily | | [News Articles](/datasets/news/) | Recent financial news with source attribution | Real-time | | [LinkedIn Metrics](/datasets/linkedin-data/) | Employee counts and follower growth | Weekly | | [App Store Ratings](/datasets/app-ratings/) | Every app a company publishes, daily | Daily | | [Reddit Mentions](/datasets/reddit-mentions/) | Ticker mentions across investing subreddits | Every 4 hours | News Sentiment and News Articles are two views of the same underlying news dataset — aggregated daily scores and article-level records respectively. ### Market & Trading Signals [Section titled “Market & Trading Signals”](#market--trading-signals) Quantitative forecasts and market activity data — price predictions, analyst views, options positioning, and insider transactions. | Dataset | Description | Update Frequency | | ------------------------------------------------------- | -------------------------------------------------------- | ---------------- | | [Price Forecasts](/datasets/ai-forecasts/) | Statistical price forecasts with confidence intervals | Daily | | [Analyst Ratings](/datasets/analyst-ratings/) | Wall Street ratings, upgrades, downgrades, price targets | Daily | | [Put/Call Ratios](/datasets/put-call/) | Options market sentiment and flow | Daily | | [Insider Transactions](/datasets/insider-transactions/) | SEC Form 4 filings tracking insider activity | Daily | ## Common Patterns [Section titled “Common Patterns”](#common-patterns) All FinBrain datasets share a consistent structure that makes them straightforward to integrate. ### Standardized Response Envelope [Section titled “Standardized Response Envelope”](#standardized-response-envelope) Every API response is wrapped in the same envelope: ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", // dataset-specific fields }, "meta": { "timestamp": "2026-04-18T12:00:00.000Z" } } ``` This means the integration code for one dataset is structurally identical to the integration code for any other. ### Ticker-Mapped at the Source [Section titled “Ticker-Mapped at the Source”](#ticker-mapped-at-the-source) Every record is mapped to a stock ticker symbol at ingestion. You can query LinkedIn metrics, lobbying filings, government contracts, and Reddit mentions all by the same `AAPL` or `MSFT` symbol — no fuzzy matching, no name resolution, no manual joining. ### Consistent Field Naming [Section titled “Consistent Field Naming”](#consistent-field-naming) Field names use camelCase across all datasets. Numeric values are returned as numbers (not strings). Dates use ISO 8601 format. This consistency matters when you’re joining datasets across endpoints in pipeline code. ### Historical Depth [Section titled “Historical Depth”](#historical-depth) Our longest-running datasets carry 10+ years of historical data, and corporate lobbying reaches back 15+ years. Newer series have shallower history and are being backfilled toward similar depth. Check individual dataset pages for exact coverage. ## Ways to Access the Data [Section titled “Ways to Access the Data”](#ways-to-access-the-data) Every dataset is delivered through four interfaces. Choose the one that fits your workflow: | Interface | Use Case | | ---------------------------------------- | --------------------------------------------------------- | | [FinBrain Terminal](/terminal/overview/) | Visual exploration, screening, ticker deep dives, no code | | [REST API](/api-reference/overview/) | Production pipelines, custom integrations, any language | | [Python SDK](/integrations/python/) | Quant research, backtesting, Jupyter workflows | | [MCP Integration](/integrations/mcp/) | LLM-powered research, AI assistants, semantic queries | The same data is available through every interface — pick whichever matches how your team works. ## Next Steps [Section titled “Next Steps”](#next-steps) * [Browse individual datasets](/datasets/ai-forecasts/) — Detailed pages with use cases and code examples * [API Reference](/api-reference/overview/) — Endpoint specifications and request/response formats * [Quick Start](/getting-started/quickstart/) — Make your first API call in minutes * [Python SDK](/integrations/python/) — Install and use the official SDK * [Terminal](/terminal/overview/) — Visual interface for exploring every dataset # Patent Filings Dataset > Access USPTO patent grant data via REST API and Python SDK. Track granted patents, technology classifications, and R&D activity by ticker since 2006. Track granted patents issued by the US Patent and Trademark Office (USPTO), mapped to publicly traded companies by ticker. Each record is an individual granted patent with its grant date, original application filing date, technology classifications, claim count, and inventors — a direct, structured signal of corporate R\&D output and innovation pace. ## What’s Included [Section titled “What’s Included”](#whats-included) The Patent Filings dataset provides, for every granted patent: * **Patent Identity**: USPTO patent number, title, type (utility, design, plant, reissue), and kind code * **Timing**: Grant date and original application filing date, plus the filing-to-grant duration in days * **Assignee**: The organization the patent is assigned to, mapped to a stock ticker, with the assignee type * **Technology Classification**: CPC sections and subsections describing the technical domain, plus the primary section * **Scope Signals**: Number of claims and forward-citation count * **Inventors**: Named inventors and the inventor count ## Coverage [Section titled “Coverage”](#coverage) | Source | Description | Update Frequency | | ------ | ------------------------------------------------- | ---------------- | | USPTO | Granted patents mapped to NYSE and NASDAQ tickers | Weekly | Patent Filings cover **US-listed companies on NYSE and NASDAQ**, with assignee organizations matched to ticker symbols at ingestion. The dataset carries **20 years of history, with granted patents dating back to 2006**, suitable for long-horizon R\&D and innovation analysis. The USPTO issues granted patents every Tuesday; each week’s grants are available in the dataset within about a day of issuance. This dataset tracks **granted patents** — patents the USPTO has issued. Each record also exposes the original `applicationFilingDate`, so you can analyze the filing-to-grant pipeline, but pending (ungranted) applications are not included. ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.patent_filings.ticker("AAPL", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" response = requests.get( f"{BASE_URL}/patent-filings/AAPL", headers={"Authorization": f"Bearer {API_KEY}"}, ) data = response.json() for patent in data["data"]["patents"]: print(f"{patent['patentDate']} {patent['patentId']} " f"[{patent['primaryCpcSection']}] {patent['title']}") ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/patent-filings/AAPL" ``` You can narrow results with `startDate`, `endDate` (both filter on the grant date, `YYYY-MM-DD`), and `limit` query parameters. For complete code examples in Python (SDK and requests), cURL, C++, Rust, and JavaScript, see the [API Reference](/api-reference/patent-filings/). ## Sample Response [Section titled “Sample Response”](#sample-response) ```json { "success": true, "data": { "symbol": "AAPL", "name": "Apple Inc.", "patents": [ { "patentId": "12345678", "patentDate": "2025-03-11", "title": "Method and apparatus for low-power display synchronization", "type": "utility", "kind": "B2", "numClaims": 20, "numCitedBy": 0, "assigneeOrganization": "Apple Inc.", "assigneeType": "2", "applicationFilingDate": "2022-06-15", "filingToGrantDays": 999, "inventors": ["John Doe", "Jane Smith"], "numInventors": 2, "cpcSections": ["G", "H"], "cpcSubsections": ["G06", "H04"], "primaryCpcSection": "G" } ] }, "meta": { "timestamp": "2026-06-16T12:00:00.000Z" } } ``` ## Key Fields [Section titled “Key Fields”](#key-fields) | Field | Description | Example | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `patentId` | USPTO patent number (globally unique) | `12345678` | | `patentDate` | Grant date (YYYY-MM-DD) | `2025-03-11` | | `title` | Patent title | `Method and apparatus for low-power display synchronization` | | `type` | Patent type | `utility` | | `kind` | USPTO kind code | `B2` | | `numClaims` | Number of claims | `20` | | `numCitedBy` | Forward-citation count | `0` | | `assigneeOrganization` | Organization the patent is assigned to | `Apple Inc.` | | `assigneeType` | Assignee type code (`2` = US company, `3` = foreign company) | `2` | | `applicationFilingDate` | Original application filing date (YYYY-MM-DD) | `2022-06-15` | | `filingToGrantDays` | Days from filing to grant | `999` | | `inventors` | Named inventors | `["John Doe", "Jane Smith"]` | | `numInventors` | Number of inventors | `2` | | `cpcSections` | CPC classification sections | `["G", "H"]` | | `cpcSubsections` | CPC subsections | `["G06", "H04"]` | | `primaryCpcSection` | Leading CPC section | `G` | | `cik` | SEC Central Index Key of the company as of this record (10-digit zero-padded, `null` when unresolved) — for joining to your own SEC-keyed data; not queryable as a parameter | `0000320193` | ## Technology Classification (CPC) [Section titled “Technology Classification (CPC)”](#technology-classification-cpc) Patents are tagged with Cooperative Patent Classification (CPC) codes describing their technical domain. The single-letter `primaryCpcSection` gives a quick read on where a company is innovating: | Section | Technology Domain | | ------- | -------------------------------------------------- | | A | Human Necessities | | B | Performing Operations; Transporting | | C | Chemistry; Metallurgy | | D | Textiles; Paper | | E | Fixed Constructions | | F | Mechanical Engineering; Lighting; Heating; Weapons | | G | Physics (computing, optics, instruments) | | H | Electricity (electronics, communications) | | Y | New / cross-sectional technologies | Subsections (e.g., `G06` for computing, `H04` for communications) add a finer level of detail. ## Use Cases [Section titled “Use Cases”](#use-cases) ### R\&D Pace Tracker [Section titled “R\&D Pace Tracker”](#rd-pace-tracker) Measure how a company’s innovation output trends over time by counting granted patents per quarter. The SDK returns a DataFrame indexed by grant date, so resampling is a one-liner: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.patent_filings.ticker("NVDA", as_dataframe=True) quarterly = df["patentId"].resample("QE").count() print(quarterly.tail(8)) ``` ### Technology Mix [Section titled “Technology Mix”](#technology-mix) See which technical domains a company is investing in by breaking patents down by their primary CPC section: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.patent_filings.ticker("TSLA", as_dataframe=True) print(df["primaryCpcSection"].value_counts()) ``` ### Innovation Leaders Scan [Section titled “Innovation Leaders Scan”](#innovation-leaders-scan) Compare granted-patent volume across a peer group to find the most prolific innovators: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def scan_patent_volume(symbols, date_from): """Rank tickers by number of patents granted since date_from.""" results = [] for symbol in symbols: try: df = fb.patent_filings.ticker(symbol, date_from=date_from, as_dataframe=True) results.append({"symbol": symbol, "patents": len(df)}) except Exception: continue return sorted(results, key=lambda x: x["patents"], reverse=True) semis = ["NVDA", "AMD", "INTC", "QCOM", "AVGO"] for r in scan_patent_volume(semis, "2024-01-01"): print(f"{r['symbol']}: {r['patents']} patents") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Patent Filings API Reference](/api-reference/patent-filings/) — Endpoint details, parameters, and response schema * [Government Contracts Dataset](/datasets/government-contracts/) — Federal contract awards mapped to tickers * [Corporate Lobbying Dataset](/datasets/corporate-lobbying/) — Track corporate influence and regulatory exposure * [Insider Transactions Dataset](/datasets/insider-transactions/) — SEC Form 4 executive trades * [Datasets Overview](/datasets/overview/) — Browse the full FinBrain dataset catalog # Put/Call Ratio Dataset > Access options put/call ratio data via REST API. Track options market sentiment and positioning for systematic trading strategies. Access options market data including put/call ratios. Track options positioning and market sentiment derived from derivatives activity for systematic trading strategies. ## What’s Included [Section titled “What’s Included”](#whats-included) The Put/Call Ratio dataset provides: * **Put/Call Ratio**: Ratio of put volume to call volume * **Volume Data**: Total puts, calls, and combined volume traded * **Price**: Underlying asset price at time of observation * **Historical Data**: Track changes in options sentiment over time * **Daily Updates**: Fresh data every trading day ## Coverage [Section titled “Coverage”](#coverage) | Coverage | Details | | ---------------- | ---------------------- | | Markets | S\&P 500, NASDAQ, NYSE | | Data Points | Volume, ratios, price | | Update Frequency | Daily | | Historical Data | 2+ years | ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.options.put_call("AAPL", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get(f"{BASE_URL}/v2/put-call-ratio/AAPL", headers=headers) result = response.json() # Access put/call data from the response envelope for entry in result["data"][:5]: print(f"{entry['date']}: Ratio {entry['ratio']} | Calls {entry['callVolume']} | Puts {entry['putVolume']}") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/put-call/). ## Visualization [Section titled “Visualization”](#visualization) Plot put/call ratio trends with the built-in SDK chart: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # One-line interactive options chart (stacked volume bars + ratio line) fb.plot.options("NVDA") ``` ![Options Put/Call Chart](/_astro/options-chart-python.CFQalwHJ.png) NVDA put/call ratio over time ## Interpreting Put/Call Ratios [Section titled “Interpreting Put/Call Ratios”](#interpreting-putcall-ratios) ### Volume Put/Call Ratio [Section titled “Volume Put/Call Ratio”](#volume-putcall-ratio) | Ratio | Interpretation | Signal | | --------- | ---------------------- | --------------------------------------------- | | > 1.2 | Excessive put buying | Contrarian bullish (fear may be overdone) | | 1.0 - 1.2 | Elevated put activity | Bearish sentiment | | 0.7 - 1.0 | Normal range | Neutral | | 0.5 - 0.7 | Elevated call activity | Bullish sentiment | | < 0.5 | Excessive call buying | Contrarian bearish (euphoria may be overdone) | ### Open Interest Put/Call Ratio [Section titled “Open Interest Put/Call Ratio”](#open-interest-putcall-ratio) Open interest ratios show longer-term positioning: * **Rising OI Ratio**: Increasing hedging/bearish positioning * **Falling OI Ratio**: Decreasing hedges/bullish positioning * **Stable OI Ratio**: Consistent market positioning ## Use Cases [Section titled “Use Cases”](#use-cases) ### Contrarian Sentiment Signal [Section titled “Contrarian Sentiment Signal”](#contrarian-sentiment-signal) Use extreme put/call readings as contrarian signals: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def get_contrarian_signal(symbol): """Generate contrarian signal from put/call ratio""" df = fb.options.put_call(symbol, as_dataframe=True) if df.empty: return None ratio = df["ratio"].iloc[0] # Calculate 20-day average for context ratios = df["ratio"].head(20) avg_ratio = ratios.mean() std_dev = ratios.std() # Z-score z_score = (ratio - avg_ratio) / std_dev if std_dev > 0 else 0 if z_score > 2: return {"signal": "contrarian_buy", "z_score": z_score, "ratio": ratio} elif z_score < -2: return {"signal": "contrarian_sell", "z_score": z_score, "ratio": ratio} else: return {"signal": "neutral", "z_score": z_score, "ratio": ratio} signal = get_contrarian_signal("AAPL") print(f"Signal: {signal['signal']} (Z-score: {signal['z_score']:.2f})") ``` ### Options Flow Scanner [Section titled “Options Flow Scanner”](#options-flow-scanner) Screen for unusual options activity: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def scan_unusual_options(tickers): """Find stocks with unusual put/call ratios""" unusual = [] for symbol in tickers: try: df = fb.options.put_call(symbol, as_dataframe=True) if df.empty: continue ratio = df["ratio"].iloc[0] date = str(df.index[0]) # Flag extremes if ratio > 1.5 or ratio < 0.4: unusual.append({ "symbol": symbol, "ratio": ratio, "signal": "high_puts" if ratio > 1.5 else "high_calls", "date": date }) except Exception: continue return sorted(unusual, key=lambda x: abs(x["ratio"] - 1), reverse=True) tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA"] unusual = scan_unusual_options(tickers) for u in unusual: print(f"{u['symbol']}: P/C Ratio {u['ratio']:.2f} - {u['signal']}") ``` ### Sentiment Trend Analysis [Section titled “Sentiment Trend Analysis”](#sentiment-trend-analysis) Track how options sentiment is changing: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def analyze_sentiment_trend(symbol, days=20): """Analyze if options sentiment is getting more bullish or bearish""" df = fb.options.put_call(symbol, as_dataframe=True) if df.empty or len(df) < days: return None recent_avg = df["ratio"].head(days // 2).mean() older_avg = df["ratio"].iloc[days // 2:days].mean() change = ((recent_avg - older_avg) / older_avg) * 100 if change > 10: trend = "increasingly_bearish" elif change < -10: trend = "increasingly_bullish" else: trend = "stable" return { "symbol": symbol, "recent_avg": recent_avg, "older_avg": older_avg, "change_percent": change, "trend": trend } trend = analyze_sentiment_trend("AAPL") print(f"Trend: {trend['trend']} (Change: {trend['change_percent']:.1f}%)") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Put/Call Data API Reference](/api-reference/put-call/) - Endpoint details, parameters, and response schema * [News Sentiment](/datasets/sentiment/) - Combine with sentiment data * [Price Forecasts](/datasets/ai-forecasts/) - Combine with forecasts # Reddit Mentions Dataset > Track stock ticker mentions across Reddit communities via REST API. Monitor retail investor buzz on WallStreetBets, r/stocks, and other subreddits with data collected every 4 hours. Python SDK included. Track how often stock tickers are discussed across Reddit investing communities. Monitor retail investor attention on WallStreetBets, r/stocks, and other subreddits with mention counts collected every 4 hours. ## What’s Included [Section titled “What’s Included”](#whats-included) The Reddit Mentions dataset provides: * **Per-Subreddit Counts**: Mention counts for each tracked subreddit (wallstreetbets, stocks, etc.) * **Aggregate Total**: Combined mentions across all subreddits via the `_all` entry * **Intraday Snapshots**: Data collected every 4 hours (6 snapshots per day) * **Cross-Market Screening**: Screener endpoint to compare mentions across tickers ## Coverage [Section titled “Coverage”](#coverage) | Source | Description | Update Frequency | | ------ | -------------------------------------------------------- | ---------------- | | Reddit | WallStreetBets, r/stocks, and other investing subreddits | Every 4 hours | ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.reddit_mentions.ticker("TSLA", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" response = requests.get( f"{BASE_URL}/reddit-mentions/TSLA", headers={"Authorization": f"Bearer {API_KEY}"} ) data = response.json() for d in data["data"]["data"]: print(f"{d['date']} {d['subreddit']}: {d['mentions']} mentions") ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/reddit-mentions/). ## Key Fields [Section titled “Key Fields”](#key-fields) | Field | Description | Example | | ----------- | --------------------------------------------- | ------------------------ | | `date` | Snapshot timestamp (ISO 8601) | 2026-03-16T14:00:00.000Z | | `subreddit` | Subreddit name, or `_all` for aggregate total | wallstreetbets | | `mentions` | Number of ticker mentions in this snapshot | 45 | Note The `_all` entry represents the total mention count across all tracked subreddits for that ticker and timestamp. It is not a real subreddit. ## Use Cases [Section titled “Use Cases”](#use-cases) ### Most Mentioned Tickers [Section titled “Most Mentioned Tickers”](#most-mentioned-tickers) Use the screener to find the most-discussed stocks across a market: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.screener.reddit_mentions(market="S&P 500", as_dataframe=True) # Sort by total mentions top = df.sort_values("totalMentions", ascending=False).head(10) for symbol, row in top.iterrows(): print(f"{symbol}: {row['totalMentions']} total mentions") ``` ### Subreddit Breakdown [Section titled “Subreddit Breakdown”](#subreddit-breakdown) See where discussion concentrates for a single ticker: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.reddit_mentions.ticker("TSLA", as_dataframe=True) # Filter out the aggregate _all rows and get latest snapshot latest = df[df["subreddit"] != "_all"].sort_values("date", ascending=False) latest_date = latest["date"].iloc[0] snapshot = latest[latest["date"] == latest_date] for _, row in snapshot.iterrows(): print(f"r/{row['subreddit']}: {row['mentions']} mentions") ``` ### Mention Velocity [Section titled “Mention Velocity”](#mention-velocity) Detect sudden spikes in retail attention by comparing snapshots over time: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.reddit_mentions.ticker("GME", as_dataframe=True) # Focus on aggregate totals totals = df[df["subreddit"] == "_all"].sort_values("date") # Calculate change between consecutive snapshots totals["prev_mentions"] = totals["mentions"].shift(1) totals["change_pct"] = ( (totals["mentions"] - totals["prev_mentions"]) / totals["prev_mentions"] * 100 ) for _, row in totals.dropna().iterrows(): if abs(row["change_pct"]) > 50: print(f"{row['date']}: {row['mentions']} mentions " f"({row['change_pct']:+.0f}% change)") ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Reddit Mentions API Reference](/api-reference/reddit-mentions/) - Endpoint details, parameters, and response schema * [News Sentiment Dataset](/datasets/sentiment/) - Sentiment scores from news articles * [Options Put/Call Dataset](/datasets/put-call/) - Options flow data * [Stock Screener API](/api-reference/screener/) - Screen data across tickers # News Sentiment Dataset > Access AI-powered news sentiment scores via REST API. Daily pre-open sentiment analysis from financial news for systematic trading strategies. Access AI-powered sentiment analysis derived from financial news. FinBrain’s NLP models process thousands of articles daily and distill each ticker’s news flow into a single daily sentiment score, helping you gauge market mood and momentum. ## What’s Included [Section titled “What’s Included”](#whats-included) The News Sentiment dataset provides: * **Sentiment Score**: Normalized numeric score from -1 (bearish) to +1 (bullish) — one score per ticker per trading day * **Array-Based Data**: Historical sentiment returned as an array of date/score objects * **Pre-Open Delivery**: Each day’s score is finalized before the US market opens and does not change intraday * **Consistent History**: The live pipeline and the historical backfill share identical scoring logic, so history matches what the live feed delivered — values are not restated * **Historical Data**: 5+ years of sentiment history (since 2021) for backtesting * **Flexible Filtering**: Filter by date range or limit the number of results ## Coverage [Section titled “Coverage”](#coverage) | Coverage | Detail | | ---------------- | ---------------------------------------------------------------------------------------------------- | | Universe | 12,000+ US-listed stocks and ETFs (NYSE and NASDAQ), including every S\&P 500 and Dow 30 constituent | | Granularity | One score per ticker per trading day | | Update Frequency | Daily, finalized before US market open | Score density follows news flow: thinly covered names carry sparser meaningful observations than large caps. Selected international markets have partial sentiment coverage; check ticker availability via the [tickers endpoint](/api-reference/available-tickers/). Sentiment scores have **5+ years of historical data** available for backtesting and trend analysis. ## Understanding Sentiment Scores [Section titled “Understanding Sentiment Scores”](#understanding-sentiment-scores) | Range | Interpretation | | ------------ | -------------------------- | | 0.5 to 1.0 | Strong bullish sentiment | | 0.2 to 0.5 | Moderate bullish sentiment | | -0.2 to 0.2 | Neutral sentiment | | -0.5 to -0.2 | Moderate bearish sentiment | | -1.0 to -0.5 | Strong bearish sentiment | Sentiment scores are returned as **numbers** in the v2 API. ## Quick Start [Section titled “Quick Start”](#quick-start) * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.sentiments.ticker("AAPL", as_dataframe=True) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" headers = {"Authorization": f"Bearer {API_KEY}"} # Get sentiment for AAPL response = requests.get(f"{BASE_URL}/sentiment/AAPL", headers=headers) result = response.json() for entry in result["data"]: print(f"{entry['date']}: {entry['score']}") ``` You can also filter by date range or limit results: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get sentiment with date range df = fb.sentiments.ticker("AAPL", date_from="2025-01-01", date_to="2025-06-30", as_dataframe=True) print(df.head(30)) ``` For complete code examples in Python, JavaScript, C++, Rust, and cURL, see the [API Reference](/api-reference/sentiment/). ## Visualization [Section titled “Visualization”](#visualization) Plot sentiment scores with the built-in SDK chart: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # One-line interactive sentiment chart fb.plot.sentiments("TSLA") ``` ![Sentiments Chart](/_astro/sentiments-chart-python.CXmnwrKX.png) TSLA news sentiment over time ## Use Cases [Section titled “Use Cases”](#use-cases) ### Sentiment-Based Trading Signals [Section titled “Sentiment-Based Trading Signals”](#sentiment-based-trading-signals) Generate trading signals based on sentiment thresholds: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def get_sentiment_signal(symbol): """Generate trading signal from sentiment score""" df = fb.sentiments.ticker(symbol, as_dataframe=True) if df.empty: return "no_data" latest_score = df["score"].iloc[0] if latest_score > 0.5: return "strong_buy" elif latest_score > 0.2: return "buy" elif latest_score < -0.5: return "strong_sell" elif latest_score < -0.2: return "sell" else: return "hold" signal = get_sentiment_signal("TSLA") print(f"Signal: {signal}") ``` ### Sentiment Screening [Section titled “Sentiment Screening”](#sentiment-screening) Screen a watchlist for tickers with extreme sentiment: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") watchlist = ["AAPL", "GOOGL", "MSFT", "AMZN", "NVDA", "TSLA"] bullish = [] bearish = [] for symbol in watchlist: df = fb.sentiments.ticker(symbol, as_dataframe=True) if not df.empty: score = df["score"].iloc[0] if score > 0.5: bullish.append((symbol, score)) elif score < -0.5: bearish.append((symbol, score)) print("Bullish tickers:", bullish) print("Bearish tickers:", bearish) ``` ### Combine with Price Predictions [Section titled “Combine with Price Predictions”](#combine-with-price-predictions) Enhance prediction confidence when sentiment aligns with expected price movement: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") def analyze_ticker(symbol): """High conviction signals when predictions and sentiment align""" # Get predictions pred_result = fb.predictions.ticker(symbol, prediction_type="daily") expected_short = pred_result["metadata"]["expectedShortTerm"] # Get sentiment sent_df = fb.sentiments.ticker(symbol, as_dataframe=True) sent_score = sent_df["score"].iloc[0] # Stronger signal when expected move and sentiment align if expected_short > 0.5 and sent_score > 0.3: return "high_conviction_buy" elif expected_short < -0.5 and sent_score < -0.3: return "high_conviction_sell" else: return "mixed_signals" result = analyze_ticker("AAPL") print(result) ``` ## Related Resources [Section titled “Related Resources”](#related-resources) * [News Sentiment API Reference](/api-reference/sentiment/) - Endpoint details, parameters, and response schema * [Price Forecasts](/datasets/ai-forecasts/) - Combine with forecasts # Enterprise & Licensing > License FinBrain's alternative datasets for your fund, platform, or team — redistribution rights, SLAs, a 30-day evaluation, and how the engagement works. Professional plans cover one user’s research. **Enterprise agreements cover your organization** — the rights to build on the data, the throughput to run it in production, and the support and SLAs institutions need. Every enterprise agreement includes the full coverage universe and full history; pricing is a flat annual rate scoped to how you’ll use it — seats, research versus production use, and redistribution rights. Contact Us ## What an enterprise agreement includes [Section titled “What an enterprise agreement includes”](#what-an-enterprise-agreement-includes) | Capability | What it means | | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | **Redistribution & display rights** | Show FinBrain data in your own products and client-facing tools | | **AI & model training rights** | Train internal models, power research copilots, and build AI products on the data | | **Contractual SLAs** | A 99.9% monthly API availability target with prioritized support response | | **Throughput at your scale** | Custom rate limits, one-time bulk historical extracts (CSV or Parquet via S3 or sFTP), and delivery sized to your backtests and pipelines | | **Dedicated account manager** | A named contact who knows your setup | ## How the engagement works [Section titled “How the engagement works”](#how-the-engagement-works) 1. **Discovery call.** Tell us what your team is building. We’ll walk through the datasets that fit, share documentation, data dictionaries, and sample files, and answer due-diligence questions. 2. **30-day evaluation.** Your team gets a trial API key with live daily data and a trailing 24 months of history across the full universe — free, for internal evaluation. We’ll agree success criteria with you up front so the trial answers the questions that matter. Production use and redistribution aren’t permitted under trial terms. 3. **Onboarding & license.** Full historical depth unlocks with your agreement, alongside your SLA, custom rate limits, and dedicated contact. ## Licensing [Section titled “Licensing”](#licensing) The standard subscription grants a limited, non-exclusive, non-transferable license for your organization’s internal business and research use. Redistribution, resale, or client-facing display of the data — raw, transformed, or aggregated — requires a separate redistribution license, negotiated per engagement. All intellectual property remains with FinBrain Technologies. Full terms are in the [Terms & Conditions](/terms-conditions). ## Coverage & history [Section titled “Coverage & history”](#coverage--history) The alternative datasets cover **12,000+ US stocks and ETFs** (NYSE and NASDAQ); price forecasts extend to **20 global markets**. History depth varies by dataset — the longest-running carry **10+ years**, corporate lobbying reaches **15+ years**, and the suite averages about **10 years**. Every dataset shares consistent ticker and date keys for cross-signal research. See the [Datasets Overview](/datasets/overview/) for per-dataset specifics. ## Support & SLAs [Section titled “Support & SLAs”](#support--slas) Enterprise subscribers receive a dedicated contact and prioritized support, plus a contractual SLA covering API availability — a **99.9% monthly target**, backed by service credits — and support response times. Daily data is delivered best-effort; on a collection outage, automated diagnostics and backfill reconstruct the affected windows. Standard support is available by email at . ## Get in touch [Section titled “Get in touch”](#get-in-touch) Tell us about your team and use case — we’ll review it and follow up to set up a discovery call. Contact Us × ## Contact Us Tell us about your team and use case. We review every inquiry and reply by email — typically within one business day. Name Work email Company Firm typeHedge Fund How do you plan to use the data? Website Send ✓ ### Thanks — your inquiry is in. Our team will review it and reach out by email shortly to set up a discovery call. Close # API Authentication > Learn how to authenticate with the FinBrain API. Supports Bearer token, X-API-Key header, and query parameter authentication methods. All FinBrain API requests require authentication using your API key. This guide explains how to obtain and use your API key. ## Getting Your API Key [Section titled “Getting Your API Key”](#getting-your-api-key) 1. Visit [finbrain.tech](https://www.finbrain.tech) and create an account 2. Navigate to your account dashboard 3. Copy your API key from the API section Your API key is a unique string that identifies your account and tracks your usage. ## Using Your API Key [Section titled “Using Your API Key”](#using-your-api-key) The FinBrain v2 API supports multiple authentication methods. Choose the one that best fits your use case: ### Bearer Token (Recommended) [Section titled “Bearer Token (Recommended)”](#bearer-token-recommended) ```plaintext Authorization: Bearer YOUR_API_KEY ``` ### X-API-Key Header [Section titled “X-API-Key Header”](#x-api-key-header) ```plaintext X-API-Key: YOUR_API_KEY ``` ### Query Parameter [Section titled “Query Parameter”](#query-parameter) ```plaintext ?apiKey=YOUR_API_KEY ``` ### Legacy Query Parameter [Section titled “Legacy Query Parameter”](#legacy-query-parameter) ```plaintext ?token=YOUR_API_KEY ``` ### Example Requests [Section titled “Example Requests”](#example-requests) * Python SDK ```python from finbrain import FinBrainClient # Initialize with your API key fb = FinBrainClient(api_key="YOUR_API_KEY") # All subsequent calls use Bearer token auth automatically predictions = fb.predictions.ticker("AAPL", as_dataframe=True) sentiment = fb.sentiments.ticker("AAPL", as_dataframe=True) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" headers = {"Authorization": f"Bearer {API_KEY}"} # Get daily predictions for Apple response = requests.get( f"{BASE_URL}/predictions/daily/AAPL", headers=headers ) data = response.json() print(data) ``` * JavaScript ```javascript const API_KEY = "YOUR_API_KEY"; const BASE_URL = "https://api.finbrain.tech/v2"; async function getPredictions(ticker) { const response = await fetch( `${BASE_URL}/predictions/daily/${ticker}`, { headers: { "Authorization": `Bearer ${API_KEY}` } } ); return response.json(); } const data = await getPredictions("AAPL"); console.log(data); ``` * cURL ```bash # Get predictions for Apple curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" # Get sentiment data curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/sentiment/AAPL" # Get insider transactions curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/insider-trading/AAPL" ``` ## API Key Security [Section titled “API Key Security”](#api-key-security) Follow these best practices to keep your API key secure: ### Do [Section titled “Do”](#do) * Store your API key in environment variables * Use secrets management in production (AWS Secrets Manager, HashiCorp Vault, etc.) * Rotate your key periodically * Use different keys for development and production ### Don’t [Section titled “Don’t”](#dont) * Commit your API key to version control * Share your API key publicly * Include your API key in client-side code * Log requests that contain your API key ### Environment Variables Example [Section titled “Environment Variables Example”](#environment-variables-example) * Python SDK ```python import os from finbrain import FinBrainClient # Reads from FINBRAIN_API_KEY env var automatically fb = FinBrainClient() ``` * Python ```python import os import requests # Load from environment variable api_key = os.environ.get("FINBRAIN_API_KEY") headers = {"Authorization": f"Bearer {api_key}"} response = requests.get( "https://api.finbrain.tech/v2/predictions/daily/AAPL", headers=headers ) ``` * JavaScript ```javascript const API_KEY = process.env.FINBRAIN_API_KEY; const response = await fetch( "https://api.finbrain.tech/v2/predictions/daily/AAPL", { headers: { "Authorization": `Bearer ${API_KEY}` } } ); ``` * Bash ```bash # Set environment variable export FINBRAIN_API_KEY="your_api_key_here" # Use in requests curl -H "Authorization: Bearer $FINBRAIN_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" ``` ## Authentication Errors [Section titled “Authentication Errors”](#authentication-errors) If authentication fails, you’ll receive one of these error responses: ### 401 Unauthorized [Section titled “401 Unauthorized”](#401-unauthorized) ```json { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Invalid or missing API key" } } ``` **Causes:** * Missing API key * Invalid API key * Expired API key **Solution:** Verify your API key is correct and included in the request. ### 403 Forbidden [Section titled “403 Forbidden”](#403-forbidden) ```json { "success": false, "error": { "code": "FORBIDDEN", "message": "Access denied for this resource" } } ``` **Causes:** * Your subscription doesn’t include this endpoint * Account suspended * Rate limit exceeded **Solution:** Check your subscription tier or contact support. ## Rate Limits [Section titled “Rate Limits”](#rate-limits) API rate limits depend on your subscription plan: | Plan | Rate Limit | | ---------- | --------------------------------------------- | | Enterprise | Custom, sized to your throughput requirements | API keys are issued under an Enterprise agreement or a scoped evaluation trial; the self-serve Professional plan is the FinBrain Terminal and does not include programmatic access. When you exceed your rate limit, you’ll receive a `429 Too Many Requests` response. Every API response includes rate limit headers so you can track your usage: | Header | Description | | ----------------------- | ------------------------------------------------ | | `X-RateLimit-Limit` | Maximum requests allowed in the current window | | `X-RateLimit-Remaining` | Requests remaining in the current window | | `X-RateLimit-Reset` | Unix timestamp when the rate limit window resets | ## Next Steps [Section titled “Next Steps”](#next-steps) * [Quick Start](/getting-started/quickstart/) - Make your first API call * [API Reference](/api-reference/overview/) - Complete endpoint documentation * [Error Codes](/api-reference/errors/) - All error responses explained # Introduction to FinBrain > FinBrain is a quantitative data platform delivering 12 alternative datasets via Terminal, REST API, Python SDK, and MCP — covering price forecasts, insider trading, congressional activity, lobbying, government contracts, sentiment, and more. FinBrain is a quantitative data platform that aggregates alternative data across equities, normalizes it, stores deep history, and delivers it however you work—visual Terminal for research, REST API for pipelines, Python SDK for strategies, MCP for AI-native workflows. **One platform. One subscription. No integration headaches.** ## What is FinBrain? [Section titled “What is FinBrain?”](#what-is-finbrain) FinBrain saves you the engineering time of aggregating, mapping, and normalizing alternative data. The infrastructure is handled so you can focus on strategy development. ### Datasets Available [Section titled “Datasets Available”](#datasets-available) **Government & Regulatory** * **Congressional Trades**: US House and Senate member trading activity from STOCK Act disclosures * **Corporate Lobbying**: Federal LDA filings tracking corporate influence and regulatory exposure * **Government Contracts**: Federal contract awards mapped to ticker symbols * **Patent Filings**: USPTO granted patents mapped to tickers, tagged by technology classification **Social & Consumer Intelligence** * **News Sentiment**: AI-powered sentiment scores derived from financial news headlines * **News Articles**: Real-time financial news with source attribution and sentiment * **LinkedIn Metrics**: Employee counts and follower growth mapped to ticker symbols * **App Store Ratings**: iOS and Android app performance mapped to public companies * **Reddit Mentions**: Ticker mentions tracked across investing subreddits **Market & Trading Signals** * **Price Forecasts**: Statistical time-series forecasts for 28,000+ tickers with daily and monthly predictions * **Analyst Ratings**: Wall Street upgrades, downgrades, and price target changes * **Options Put/Call Ratios**: Options market sentiment and flow signals * **Insider Trading**: Daily SEC Form 4 filings tracking executive purchases and sales ### What Makes FinBrain Different [Section titled “What Makes FinBrain Different”](#what-makes-finbrain-different) * **Ticker-mapped alternative data**: LinkedIn metrics, app ratings, and other datasets mapped to ticker symbols—data not found elsewhere in this format * **Deep history**: An average of 10 years of historical data for comprehensive backtesting * **Normalized and clean**: Consistent field names, data types, and update schedules across all datasets * **Multiple access methods**: Same data via Terminal, API, SDK, or MCP—use what fits your workflow ## Who is FinBrain For? [Section titled “Who is FinBrain For?”](#who-is-finbrain-for) FinBrain is built for: * **Quantitative Researchers**: Backtest trading strategies with years of historical alternative data * **Systematic Traders**: Build automated trading systems with clean, normalized data feeds * **Platform Builders**: Integrate alternative data into financial applications and dashboards * **Quantitative Developers**: Build data pipelines with our REST API and Python SDK * **Hedge Funds & Institutions**: Differentiated, ticker-mapped datasets for systematic research * **AI/LLM Developers**: Query financial data semantically via MCP integration * **Professional Traders**: Gain institutional-quality insights through the visual Terminal ## Getting Started [Section titled “Getting Started”](#getting-started) Getting started with FinBrain takes just a few minutes: ### 1. Get Your API Key [Section titled “1. Get Your API Key”](#1-get-your-api-key) Sign up at [terminal.finbrain.tech](https://terminal.finbrain.tech) to receive your API key. Institutional teams can [contact us](/enterprise/) for a scoped 30-day evaluation. ### 2. Choose Your Integration Method [Section titled “2. Choose Your Integration Method”](#2-choose-your-integration-method) * Python SDK The easiest way to access FinBrain data is through our official Python SDK: ```bash pip install finbrain-python ``` ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get price forecasts for Apple as DataFrame df = fb.predictions.ticker("AAPL", prediction_type="daily", as_dataframe=True) print(df) # mid lower upper # date # 2025-11-04 201.33 197.21 205.45 # 2025-11-05 202.77 196.92 208.61 ``` * REST API Access the API directly with any HTTP client: ```bash curl -H "Authorization: Bearer YOUR_API_KEY" "https://api.finbrain.tech/v2/predictions/daily/AAPL" ``` ```javascript const response = await fetch( "https://api.finbrain.tech/v2/predictions/daily/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const data = await response.json(); console.log(data); ``` * MCP Integration For AI assistants and Claude integration, use the MCP server: ```bash pip install finbrain-mcp ``` Configure in your Claude Desktop or AI assistant settings. ### 3. Explore the Data [Section titled “3. Explore the Data”](#3-explore-the-data) All datasets are available through both programmatic access and the visual Terminal: | Dataset | Description | Update Frequency | | --------------------------------------------------------- | ----------------------------------------------------- | ---------------- | | [Congressional Trading](/datasets/congressional-trading/) | US House and Senate member trading activity | As filed | | [Corporate Lobbying](/datasets/corporate-lobbying/) | Federal lobbying disclosures | Quarterly | | [Government Contracts](/datasets/government-contracts/) | Federal contract awards | Daily | | [Patent Filings](/datasets/patent-filings/) | USPTO granted patents mapped to ticker symbols | Weekly | | [News Sentiment](/datasets/sentiment/) | AI-generated sentiment scores from financial news | Daily | | [News Articles](/datasets/news/) | Recent financial news with source attribution | Real-time | | [LinkedIn Metrics](/datasets/linkedin-data/) | Employee counts and follower growth | Weekly | | [App Ratings](/datasets/app-ratings/) | iOS and Android app performance | Weekly | | [Reddit Mentions](/datasets/reddit-mentions/) | Ticker mentions across investing subreddits | Every 4 hours | | [Price Forecasts](/datasets/ai-forecasts/) | Statistical price forecasts with confidence intervals | Daily | | [Analyst Ratings](/datasets/analyst-ratings/) | Wall Street ratings and price targets | Daily | | [Put/Call Ratios](/datasets/put-call/) | Options market sentiment and flow | Daily | | [Insider Transactions](/datasets/insider-transactions/) | SEC Form 4 filings | Daily | ### 4. Use the Terminal [Section titled “4. Use the Terminal”](#4-use-the-terminal) The [FinBrain Terminal](https://terminal.finbrain.tech) is a web-based platform for FinBrain’s 12 alternative datasets, giving you visual access to all of them plus a wide range of macro and geopolitical context — no coding or installation required: * **Real-time Dashboard** — Market command center with price forecast signals, earnings calendar, treasury yields, and Reddit mention rankings * **Geopolitical Intelligence** — Interactive globe with global events, OSINT-style intel feed, and CFTC futures positioning across asset classes * **Markets Dashboards** — Dedicated views for Equities, Fixed Income, Commodities, Currencies, and Crypto with macro indicators and yield curves * **Ticker Deep Dive** — Every dataset for any ticker — forecasts with confidence intervals, sentiment, insider trades, lobbying, contracts, and Reddit activity * **15 Alternative Data Screeners** — Filter 12,000+ US tickers by price forecasts, insider buying, congressional trades, lobbying, government contracts, Reddit mentions, and more * **Portfolio Tracking** — Real-time PnL, equity curves, sector allocation, and benchmark comparison Just log in and start exploring. [Learn more](/terminal/overview/). ## Base URL [Section titled “Base URL”](#base-url) All API requests are made to: ```plaintext https://api.finbrain.tech/v2/ ``` ## Authentication [Section titled “Authentication”](#authentication) The preferred authentication method is via the `Authorization` header: ```plaintext Authorization: Bearer YOUR_API_KEY ``` The API supports multiple authentication methods. See the [Authentication](/getting-started/authentication/) page for details. ## Next Steps [Section titled “Next Steps”](#next-steps) * [Authentication](/getting-started/authentication/) - Learn about API key authentication * [Quick Start](/getting-started/quickstart/) - Make your first API call * [API Reference](/api-reference/overview/) - Complete endpoint documentation * [Python SDK](/integrations/python/) - SDK installation and usage * [Terminal](/terminal/overview/) - Visual dashboard for research # Quick Start Guide > Get started with the FinBrain API in minutes. Make your first API call and retrieve price forecasts, insider trading data, and sentiment scores. This guide walks you through making your first FinBrain API calls. By the end, you’ll know how to retrieve price forecasts, insider trading data, and sentiment scores. ## Prerequisites [Section titled “Prerequisites”](#prerequisites) * A FinBrain API key ([sign up here](https://www.finbrain.tech)) * Python 3.7+ or any HTTP client ## Step 1: Set Up Authentication [Section titled “Step 1: Set Up Authentication”](#step-1-set-up-authentication) All FinBrain API v2 endpoints use Bearer token authentication. Include your API key in the `Authorization` header of every request: ```plaintext Authorization: Bearer YOUR_API_KEY ``` ## Step 2: Set Up Your Environment [Section titled “Step 2: Set Up Your Environment”](#step-2-set-up-your-environment) ```python import requests API_KEY = "YOUR_API_KEY" headers = {"Authorization": f"Bearer {API_KEY}"} ``` ## Step 3: Fetch Data [Section titled “Step 3: Fetch Data”](#step-3-fetch-data) ### Get Price Forecasts [Section titled “Get Price Forecasts”](#get-price-forecasts) Retrieve statistical price forecasts for any ticker: * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get daily predictions for Apple as DataFrame df = fb.predictions.ticker("AAPL", prediction_type="daily", as_dataframe=True) print(df) # mid lower upper # date # 2025-11-04 201.33 197.21 205.45 # 2025-11-05 202.77 196.92 208.61 ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get( "https://api.finbrain.tech/v2/predictions/daily/AAPL", headers=headers ) data = response.json() print(data) ``` **Sample JSON Output:** ```json { "success": true, "data": { "ticker": "AAPL", "name": "Apple Inc.", "predictions": [ { "date": "2025-11-04", "mid": 201.33, "lower": 197.21, "upper": 205.45 }, { "date": "2025-11-05", "mid": 202.77, "lower": 196.92, "upper": 208.61 }, { "date": "2025-11-06", "mid": 203.99, "lower": 196.90, "upper": 211.08 } ], "metadata": { "expectedShortTerm": 0.22, "expectedMidTerm": 0.58, "expectedLongTerm": 0.25, "type": "daily", "lastUpdated": "2025-11-01T23:24:18.371Z" } }, "meta": { "timestamp": "2025-11-02T10:15:30.000Z" } } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/predictions/daily/AAPL", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const data = await response.json(); console.log(data); ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/predictions/daily/AAPL" ``` ### Get Insider Trading Data [Section titled “Get Insider Trading Data”](#get-insider-trading-data) Track executive purchases and sales from SEC Form 4 filings: * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get insider transactions for Tesla as DataFrame df = fb.insider_transactions.ticker("TSLA", as_dataframe=True) print(df.head()) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get( "https://api.finbrain.tech/v2/insider-trading/TSLA", headers=headers ) data = response.json() print(data) ``` **Sample JSON Output:** ```json { "success": true, "data": { "ticker": "TSLA", "name": "Tesla Inc.", "transactions": [ { "date": "2025-01-10", "insider": "Elon Musk", "relationship": "CEO", "transactionType": "Sale", "pricePerShare": 245.50, "shares": 50000, "totalValue": 12275000, "sharesOwned": 715000000, "filingUrl": "https://sec.gov/..." } ] }, "meta": { "timestamp": "2025-01-12T08:30:00.000Z" } } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/insider-trading/TSLA", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const data = await response.json(); console.log(data); ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/insider-trading/TSLA" ``` ### Get Sentiment Scores [Section titled “Get Sentiment Scores”](#get-sentiment-scores) Access AI-powered sentiment analysis from financial news: * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get sentiment for Microsoft as DataFrame df = fb.sentiments.ticker("MSFT", as_dataframe=True) print(df.tail()) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get( "https://api.finbrain.tech/v2/sentiment/MSFT", headers=headers ) data = response.json() print(data) ``` **Sample JSON Output:** ```json { "success": true, "data": { "ticker": "MSFT", "name": "Microsoft Corporation", "sentiments": [ { "date": "2025-01-15", "score": 0.72 }, { "date": "2025-01-14", "score": 0.68 }, { "date": "2025-01-13", "score": 0.65 }, { "date": "2025-01-12", "score": 0.70 }, { "date": "2025-01-11", "score": 0.63 } ] }, "meta": { "timestamp": "2025-01-16T06:00:00.000Z" } } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/sentiment/MSFT", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const data = await response.json(); console.log(data); ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/sentiment/MSFT" ``` ### Get Congressional Trades [Section titled “Get Congressional Trades”](#get-congressional-trades) Monitor US House Representatives trading activity: * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") # Get House trades for NVIDIA as DataFrame df = fb.house_trades.ticker("NVDA", as_dataframe=True) print(df.head()) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get( "https://api.finbrain.tech/v2/congress/house/NVDA", headers=headers ) data = response.json() print(data) ``` **Sample JSON Output:** ```json { "success": true, "data": { "ticker": "NVDA", "name": "NVIDIA Corporation", "trades": [ { "date": "2025-01-08", "politician": "Nancy Pelosi", "transactionType": "Purchase", "amount": "$1,000,001 - $5,000,000", "chamber": "house" } ] }, "meta": { "timestamp": "2025-01-10T12:00:00.000Z" } } ``` * JavaScript ```javascript const response = await fetch( "https://api.finbrain.tech/v2/congress/house/NVDA", { headers: { "Authorization": "Bearer YOUR_API_KEY" } } ); const data = await response.json(); console.log(data); ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/congress/house/NVDA" ``` ## Step 4: Filter by Date Range [Section titled “Step 4: Filter by Date Range”](#step-4-filter-by-date-range) Most endpoints support date filtering: * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") df = fb.sentiments.ticker( "AAPL", date_from="2025-01-01", date_to="2025-01-31", as_dataframe=True ) print(df) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get( "https://api.finbrain.tech/v2/sentiment/AAPL", headers=headers, params={"startDate": "2025-01-01", "endDate": "2025-01-31"} ) data = response.json() print(data) ``` * cURL ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.finbrain.tech/v2/sentiment/AAPL?startDate=2025-01-01&endDate=2025-01-31" ``` ## Complete Example [Section titled “Complete Example”](#complete-example) Here’s a complete script that fetches multiple datasets for a ticker: * Python SDK ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_API_KEY") ticker = "AAPL" print(f"Analyzing {ticker}...\n") # Price Forecasts predictions_df = fb.predictions.ticker(ticker, as_dataframe=True) print("Price Forecasts:") print(predictions_df.head()) # Insider Transactions insiders_df = fb.insider_transactions.ticker(ticker, as_dataframe=True) print("\nInsider Transactions:") print(insiders_df.head()) # Sentiment sentiment_df = fb.sentiments.ticker(ticker, as_dataframe=True) print("\nSentiment Scores:") print(sentiment_df.tail()) # Congressional Trades trades_df = fb.house_trades.ticker(ticker, as_dataframe=True) print("\nCongressional Trades:") print(trades_df.head()) ``` * Python (requests) ```python import requests API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.finbrain.tech/v2" headers = {"Authorization": f"Bearer {API_KEY}"} ticker = "AAPL" print(f"Analyzing {ticker}...\n") # Price Forecasts resp = requests.get(f"{BASE_URL}/predictions/daily/{ticker}", headers=headers) predictions = resp.json() if predictions["success"]: for p in predictions["data"]["predictions"][:3]: print(f" {p['date']}: mid={p['mid']}, range=[{p['lower']}, {p['upper']}]") # Insider Transactions resp = requests.get(f"{BASE_URL}/insider-trading/{ticker}", headers=headers) insiders = resp.json() if insiders["success"]: print("\nInsider Transactions:") for txn in insiders["data"]["transactions"][:3]: print(f" {txn['date']}: {txn['insider']} - {txn['transactionType']} " f"{txn['shares']} shares @ ${txn['pricePerShare']}") # Sentiment resp = requests.get(f"{BASE_URL}/sentiment/{ticker}", headers=headers) sentiment = resp.json() if sentiment["success"]: print("\nSentiment Scores:") for s in sentiment["data"]["sentiments"][:5]: print(f" {s['date']}: {s['score']}") # Congressional Trades resp = requests.get(f"{BASE_URL}/congress/house/{ticker}", headers=headers) congress = resp.json() if congress["success"]: print("\nCongressional Trades:") for t in congress["data"]["trades"][:3]: print(f" {t['date']}: {t['politician']} - {t['transactionType']} ({t['amount']})") ``` ## Next Steps [Section titled “Next Steps”](#next-steps) Now that you’ve made your first API calls, explore more: * [Datasets](/datasets/ai-forecasts/) - Detailed dataset documentation * [API Reference](/api-reference/overview/) - Complete endpoint reference * [Python SDK](/integrations/python/) - Full SDK documentation # MCP Integration Guide > Integrate FinBrain financial data with AI assistants using the Model Context Protocol (MCP). Connect Claude Desktop, VS Code, and other MCP-compatible AI tools. A **Model Context Protocol (MCP)** server that exposes FinBrain datasets to AI clients (Claude Desktop, VS Code MCP extensions, etc.) via simple tools. Backed by the official **finbrain-python** SDK (v0.2.0+, using the v2 API). * **Package name:** `finbrain-mcp` * **CLI entrypoint:** `finbrain-mcp` * **GitHub:** [github.com/ahmetsbilgin/finbrain-mcp](https://github.com/ahmetsbilgin/finbrain-mcp) ## How It Fits Together [Section titled “How It Fits Together”](#how-it-fits-together) Your side MCP clients Whatever your team already uses * Claude Desktop * VS Code, Copilot agent mode * Custom LLM apps and copilots MCP Your side finbrain-mcp Runs in your environment * pip install finbrain-mcp, or Docker * Launched by the client as a local process * API key from the environment * 33 tools for the model to call * JSON by default, CSV on request HTTPS Our side FinBrain v2 API api.finbrain.tech * Built on finbrain-python * 12 datasets, one envelope and one key * Entitlements and rate limits per key The server runs where you run it. Your prompts stay inside your environment — only the data request crosses the boundary. ## Video Tutorial [Section titled “Video Tutorial”](#video-tutorial) Watch how to use FinBrain’s MCP integration for LLM-based stock research: [How to use alternative financial data for LLM-based stock research](https://www.youtube.com/embed/htApNnmgXJI) ## Features [Section titled “Features”](#features) ### Price Forecasts [Section titled “Price Forecasts”](#price-forecasts) Access FinBrain’s statistical time-series price forecasts with daily (10-day) and monthly (12-month) horizons. Includes mid predictions with calibrated upper and lower bounds. ### News Sentiment Analysis [Section titled “News Sentiment Analysis”](#news-sentiment-analysis) Track aggregated sentiment scores derived from financial news coverage. Monitor how market sentiment shifts over time for any ticker. ### Alternative Data [Section titled “Alternative Data”](#alternative-data) * **LinkedIn Metrics** — Employee count and follower trends as company health indicators * **App Store Ratings** — Mobile app performance data for consumer-facing companies * **Options Flow** — Put/call ratios and volume to gauge market positioning * **Reddit Mentions** — Ticker mention counts across Reddit investing communities ### Institutional & Insider Activity [Section titled “Institutional & Insider Activity”](#institutional--insider-activity) * **US Congress Trades** — Stock transactions disclosed by House representatives and Senators * **Insider Transactions** — SEC Form 4 filings showing executive buys and sells * **Analyst Ratings** — Wall Street coverage and price target changes * **Corporate Lobbying** — Federal lobbying disclosures with registrant details and expenditures * **Government Contracts** — Federal contract awards from USAspending.gov mapped to tickers * **Patent Filings** — USPTO granted patents mapped to tickers, with CPC classification ## Available Tools [Section titled “Available Tools”](#available-tools) The MCP server exposes 33 tools to AI assistants: ### Discovery & Availability [Section titled “Discovery & Availability”](#discovery--availability) | Tool | Description | | ------------------- | ---------------------------------- | | `health` | Check server status and version | | `available_markets` | List all available markets | | `available_tickers` | List tickers for a prediction type | | `available_regions` | List markets grouped by region | ### Per-Ticker Data [Section titled “Per-Ticker Data”](#per-ticker-data) | Tool | Description | | -------------------------------- | ----------------------------------------------------------------------------------- | | `predictions_by_ticker` | Price forecasts with confidence intervals | | `news_sentiment_by_ticker` | Daily sentiment scores over time | | `news_by_ticker` | Recent news articles for a ticker | | `analyst_ratings_by_ticker` | Wall Street analyst ratings and price targets | | `house_trades_by_ticker` | US House Representatives trades | | `senate_trades_by_ticker` | US Senate trades | | `insider_transactions_by_ticker` | SEC Form 4 insider transactions | | `linkedin_metrics_by_ticker` | LinkedIn employee and follower data | | `app_ratings_by_ticker` | App Store and Play Store ratings, plus a summary of every app the company publishes | | `options_put_call` | Put/call ratio and volume data | | `corporate_lobbying_by_ticker` | Corporate lobbying filings (LDA disclosures) | | `reddit_mentions_by_ticker` | Reddit mention counts by subreddit | | `government_contracts_by_ticker` | Federal contract awards mapped to a ticker | | `patent_filings_by_ticker` | USPTO granted patents mapped to a ticker | ### Cross-Ticker Screeners [Section titled “Cross-Ticker Screeners”](#cross-ticker-screeners) | Tool | Description | | ------------------------------- | --------------------------------------------------------------- | | `predictions_by_market` | Screen predictions across tickers by market or region | | `screener_sentiment` | Screen sentiment across tickers (requires market or region) | | `screener_analyst_ratings` | Screen analyst ratings across tickers | | `screener_insider_trading` | Screen insider trades across tickers | | `screener_house_trades` | Screen House trades across tickers | | `screener_senate_trades` | Screen Senate trades across tickers | | `screener_news` | Screen news across tickers | | `screener_put_call_ratio` | Screen put/call ratios across tickers | | `screener_linkedin` | Screen LinkedIn data across tickers (requires market or region) | | `screener_app_ratings` | Screen app ratings across tickers (requires market or region) | | `screener_reddit_mentions` | Screen Reddit mentions across tickers | | `screener_government_contracts` | Screen government contract awards across tickers | | `screener_patent_filings` | Screen patent filings across tickers | ### Recent Activity [Section titled “Recent Activity”](#recent-activity) | Tool | Description | | ------------------------ | ------------------------------------------------ | | `recent_news` | Latest news articles across all tracked stocks | | `recent_analyst_ratings` | Latest analyst ratings across all tracked stocks | All tools return JSON by default, with optional CSV output. ## Installation [Section titled “Installation”](#installation) ```bash pip install finbrain-mcp ``` ## Configuration [Section titled “Configuration”](#configuration) ### Claude Desktop [Section titled “Claude Desktop”](#claude-desktop) Edit your Claude Desktop config file: * macOS Edit `~/Library/Application Support/Claude/claude_desktop_config.json`: ```json { "mcpServers": { "finbrain": { "command": "finbrain-mcp", "env": { "FINBRAIN_API_KEY": "YOUR_KEY" } } } } ``` * Windows Edit `%APPDATA%\Claude\claude_desktop_config.json`: ```json { "mcpServers": { "finbrain": { "command": "finbrain-mcp", "env": { "FINBRAIN_API_KEY": "YOUR_KEY" } } } } ``` * Linux Edit `~/.config/Claude/claude_desktop_config.json`: ```json { "mcpServers": { "finbrain": { "command": "finbrain-mcp", "env": { "FINBRAIN_API_KEY": "YOUR_KEY" } } } } ``` After saving the configuration, **quit and reopen Claude Desktop**. **macOS tip:** If `"command": "finbrain-mcp"` doesn’t work, find and use the full path: ```bash which finbrain-mcp ``` Then use that path in your config: ```json { "mcpServers": { "finbrain": { "command": "/full/path/to/finbrain-mcp", "env": { "FINBRAIN_API_KEY": "YOUR_KEY" } } } } ``` ### VS Code [Section titled “VS Code”](#vs-code) 1. Open the Command Palette → **“MCP: Open User Configuration”** 2. Add the server under the `servers` key: ```json { "servers": { "finbrain": { "command": "finbrain-mcp", "env": { "FINBRAIN_API_KEY": "YOUR_KEY" } } } } ``` 3. In Copilot Chat, enable Agent Mode to use MCP tools. ### Docker [Section titled “Docker”](#docker) ```bash # Build the image docker build -t finbrain-mcp:latest . # Run with your API key docker run --rm -e FINBRAIN_API_KEY="YOUR_KEY" finbrain-mcp:latest ``` Claude Desktop config for Docker: ```json { "mcpServers": { "finbrain": { "command": "docker", "args": ["run", "-i", "--rm", "finbrain-mcp:latest"], "env": { "FINBRAIN_API_KEY": "YOUR_KEY" } } } } ``` ## Example Prompts [Section titled “Example Prompts”](#example-prompts) You don’t need to know tool names—just ask in plain English: ### Predictions [Section titled “Predictions”](#predictions) * “Get FinBrain’s **daily predictions** for **AMZN**.” * “Show **monthly predictions** (12-month horizon) for **AMZN**.” * “Get **market-wide daily predictions** for **S\&P 500** tickers.” ### News & Sentiment [Section titled “News & Sentiment”](#news--sentiment) * “What’s the **news sentiment** for **AMZN** from 2025-01-01 to 2025-03-31?” * “Get **recent news articles** for **AMZN**.” * “Export AMZN news sentiment for 2025 YTD **as CSV**.” ### App Ratings [Section titled “App Ratings”](#app-ratings) * “Fetch **app store ratings** for **UBER** between 2026-09-01 and 2026-09-30.” * “Which **apps** does **AAPL** publish, and which is the biggest?” * “Show the rating history of **Shazam** for **AAPL**.” The tool returns the blended company series plus an `apps` summary — one line per app with its id, name, observation count and latest score. Ask for a specific app and the assistant passes its `app_id` to get that app’s own series, so a company with a hundred apps does not flood the conversation. ### Analyst Ratings [Section titled “Analyst Ratings”](#analyst-ratings) * “List **analyst ratings** for **AAPL** in Q1 2025.” ### Congressional Trades [Section titled “Congressional Trades”](#congressional-trades) * “Show **recent House trades** involving **NVDA**.” * “Show **recent Senate trades** involving **META**.” ### Insider Transactions [Section titled “Insider Transactions”](#insider-transactions) * “Recent **insider transactions** for **TSLA**?” ### Corporate Lobbying [Section titled “Corporate Lobbying”](#corporate-lobbying) * “Show **corporate lobbying filings** for **AAPL**.” * “Which **lobbying firms** represent **GOOGL**?” ### Government Contracts [Section titled “Government Contracts”](#government-contracts) * “Show recent **government contracts** awarded to **LMT**.” * “Which agencies award the most contracts to **RTX**?” ### Patent Filings [Section titled “Patent Filings”](#patent-filings) * “Show recent **patent filings** for **AAPL**.” * “Which companies have the **most granted patents** lately?” ### LinkedIn Metrics [Section titled “LinkedIn Metrics”](#linkedin-metrics) * “Get **LinkedIn employee & follower counts** for **META** (last 12 months).” ### Options Put/Call [Section titled “Options Put/Call”](#options-putcall) * “What’s the **put/call ratio** for **SPY** over the last 60 days?” ### Screeners [Section titled “Screeners”](#screeners) * “Screen **sentiment** across **S\&P 500** stocks.” * “Screen **insider trading** across all tickers.” * “Screen **LinkedIn data** for **US** region stocks.” * “Screen **app ratings** for **NASDAQ** tickers.” ### Recent Activity [Section titled “Recent Activity”](#recent-activity-1) * “Show the **latest news** across all tracked stocks.” * “What are the **most recent analyst ratings**?” ### Availability [Section titled “Availability”](#availability) * “Which **markets** are available?” * “List **tickers** in the **daily** predictions universe.” * “Show available **regions** and their markets.” **Notes:** * Date format: `YYYY-MM-DD` * Time-series endpoints return the most recent N points by default—say “limit 200” to get more * Predictions horizon: **daily** (10-day) or **monthly** (12-month) * Say “**as CSV**” to receive CSV instead of JSON ## Troubleshooting [Section titled “Troubleshooting”](#troubleshooting) ### Server Not Starting (ENOENT) [Section titled “Server Not Starting (ENOENT)”](#server-not-starting-enoent) Wrong path in client config. Use the exact path: ```bash # Find the path which finbrain-mcp # macOS/Linux where finbrain-mcp # Windows ``` ### API Key Not Configured [Section titled “API Key Not Configured”](#api-key-not-configured) Put `FINBRAIN_API_KEY` in the client’s `env` block (recommended), or set it as an environment variable: ```bash # macOS/Linux export FINBRAIN_API_KEY="YOUR_KEY" # Windows (PowerShell) $env:FINBRAIN_API_KEY="YOUR_KEY" # Windows (persistent) setx FINBRAIN_API_KEY "YOUR_KEY" ``` Then fully restart your MCP client. ### Checking Logs [Section titled “Checking Logs”](#checking-logs) Claude Desktop logs can help diagnose issues: * **macOS**: `~/Library/Logs/Claude/mcp*.log` * **Windows**: `%APPDATA%\Claude\logs\mcp*.log` ## Related Resources [Section titled “Related Resources”](#related-resources) * [Python SDK](/integrations/python/) * [API Reference](/api-reference/overview/) * [Quick Start Guide](/getting-started/quickstart/) # Python SDK Documentation > Official Python SDK for the FinBrain API v2. Install with pip and access price forecasts, insider trading, sentiment analysis, and alternative data. 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](https://pypi.org/project/finbrain-python/) * **GitHub:** [github.com/ahmetsbilgin/finbrain-python](https://github.com/ahmetsbilgin/finbrain-python) ## Features [Section titled “Features”](#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=True` on every endpoint for pandas DataFrames * MIT-licensed, fully unit-tested ## Installation [Section titled “Installation”](#installation) ```bash pip install finbrain-python ``` ## Quick Start [Section titled “Quick Start”](#quick-start) ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_KEY") # create once, reuse below # ---------- discovery ---------- fb.available.markets() # list markets fb.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 ---------- # History begins 2026-09-03 (daily, per app) fb.app_ratings.ticker("AMZN", date_from="2026-09-01", date_to="2026-09-30", as_dataframe=True) # per_app=True returns one row per app per date, for companies # that publish more than one app fb.app_ratings.ticker("AAPL", date_from="2026-09-01", date_to="2026-09-30", as_dataframe=True, per_app=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) # ---------- government contracts ---------- fb.government_contracts.ticker("LMT", date_from="2025-01-01", date_to="2025-12-31", as_dataframe=True) # ---------- patent filings ---------- fb.patent_filings.ticker("AAPL", date_from="2025-01-01", date_to="2025-12-31", limit=50, 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) fb.screener.government_contracts(as_dataframe=True) fb.screener.patent_filings(limit=100, 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”](#async-usage) For async/await support, install with the `async` extra: ```bash pip install finbrain-python[async] ``` Then use `AsyncFinBrainClient` with `httpx`: ```python import asyncio from 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”](#plotting) Plot helpers for visualizing FinBrain data. All plot methods support: * `show` – defaults to True, so the chart appears immediately * `as_json=True` – skips display and returns the figure as a Plotly-JSON string * `template` – Plotly template name (default: `"plotly_dark"`) ```python # ---------- App Ratings Chart - Apple App Store or Google Play Store ---------- # Pass app_id=... to chart one specific app rather than the biggest on that store fb.plot.app_ratings("AMZN", store="app", # "play" for Google Play Store date_from="2026-09-01", date_to="2026-09-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 chart fb.plot.insider_transactions("AAPL", price_data=price_df) # Plot House member trades on your price chart fb.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 chart fb.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 chart fb.plot.corporate_lobbying("AAPL", price_data=price_df, date_from="2025-01-01", date_to="2025-06-30") # Plot patent grants on your price chart fb.plot.patent_filings("AAPL", price_data=price_df, date_from="2024-01-01", date_to="2025-06-30") ``` **Price Data Requirements:** * DataFrame with DatetimeIndex * Must contain a price column: `close`, `Close`, `price`, `Price`, `adj_close`, or `Adj Close` * Obtain from legal sources: broker API, Bloomberg, Alpha Vantage, FMP, etc. ## Authentication [Section titled “Authentication”](#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.)* 1. Subscribe at [finbrain.tech](https://www.finbrain.tech) → FinBrain API 2. Copy the key from your dashboard 3. Pass it once when you create the client: ```python from finbrain import FinBrainClient fb = FinBrainClient(api_key="YOUR_KEY") ``` Or set the `FINBRAIN_API_KEY` environment variable and omit it: ```python fb = FinBrainClient() # reads from FINBRAIN_API_KEY env var ``` The SDK uses Bearer token authentication (`Authorization: Bearer YOUR_KEY`) automatically. ## Client Options [Section titled “Client Options”](#client-options) ```python 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`: ```python predictions = fb.predictions.ticker("AAPL", as_dataframe=True) print(fb.last_meta) # {"timestamp": "2026-03-09T12:34:56Z"} ``` ## Supported Endpoints [Section titled “Supported Endpoints”](#supported-endpoints) ### Per-Ticker Endpoints [Section titled “Per-Ticker Endpoints”](#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`, `owner`, `disclosureDate` | | Senate trades | `client.senate_trades.ticker(symbol)` | `politician`, `transactionType`, `amount`, `owner`, `disclosureDate` | | Analyst ratings | `client.analyst_ratings.ticker(symbol)` | `action`, `institution`, `rating`, `targetPrice` | | Options | `client.options.put_call(symbol)` | `ratio`, `callVolume`, `putVolume` | | LinkedIn | `client.linkedin_data.ticker(symbol)` | `employeeCount`, `followerCount` | | App ratings | `client.app_ratings.ticker(symbol)` | `ios_score`, `android_score`, `android_installCount` | | App ratings (per app) | `client.app_ratings.ticker(symbol, per_app=True)` | `platform`, `app_id`, `app_name`, `score`, `ratings_count`, `install_count` | | Corporate lobbying | `client.corporate_lobbying.ticker(symbol)` | `clientName`, `registrantName`, `income`, `expenses`, `issueCodes` | | Government contracts | `client.government_contracts.ticker(symbol)` | `awardAmount`, `awardingAgency`, `recipientName`, `naicsCode` | | Patent filings | `client.patent_filings.ticker(symbol)` | `title`, `type`, `primaryCpcSection`, `numClaims`, `filingToGrantDays` | ### Discovery Endpoints [Section titled “Discovery Endpoints”](#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”](#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()` | | | `client.screener.reddit_mentions()` | | | `client.screener.government_contracts()` | | | `client.screener.patent_filings()` | | Recent | `client.recent.news()` | | | `client.recent.analyst_ratings()` | See [API Reference](/api-reference/overview/) for endpoint paths and parameters. ## Error Handling [Section titled “Error Handling”](#error-handling) ```python 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 details except 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”](#migration-from-v01x) 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”](#development) ```bash git clone https://github.com/ahmetsbilgin/finbrain-python cd finbrain-python python -m venv .venv && source .venv/bin/activate pip install -e .[dev] ruff check . # lint / format pytest -q # unit tests (mocked) ``` ## Security [Section titled “Security”](#security) Report vulnerabilities to ****. We respond within 48 hours. ## Related Resources [Section titled “Related Resources”](#related-resources) * [Quick Start Guide](/getting-started/quickstart/) * [API Reference](/api-reference/overview/) * [MCP Integration](/integrations/mcp/) # Privacy Policy ## Introduction [Section titled “Introduction”](#introduction) FinBrain Technologies (“FinBrain,” “we,” “us,” or “our”) is committed to protecting your privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard information when you use the FinBrain website (finbrain.tech), FinBrain Terminal (terminal.finbrain.tech), FinBrain REST API, Python SDK, Model Context Protocol (MCP) integration, and all related services (collectively, the “Services”). By using the Services, you consent to the data practices described in this policy. If you do not agree with this policy, please do not use the Services. ## Scope [Section titled “Scope”](#scope) This Privacy Policy applies to information we collect: * From individuals who visit our websites, create accounts, subscribe to plans, or contact us * Through automated means (cookies, logs, analytics) when you interact with the Services * From third parties who provide us with account or payment information This policy does not apply to the underlying market data served through the Services, which relates to publicly traded companies and public disclosures, not to you personally. ## Information We Collect [Section titled “Information We Collect”](#information-we-collect) ### Information You Provide [Section titled “Information You Provide”](#information-you-provide) We collect information you voluntarily provide when you: * Create an account or subscribe to our Services * Contact us for support, sales, or general inquiries * Subscribe to our newsletter, blog, or updates * Provide feedback, testimonials, or participate in surveys This information may include: * Name and email address * Billing information and payment details (processed by our payment processor) * Company name, role, and professional context * Communication preferences * Content you submit to us (support tickets, feedback, inquiries) ### Information Collected Automatically [Section titled “Information Collected Automatically”](#information-collected-automatically) When you use the Services, we automatically collect: * IP address and approximate geographic location * Browser type, version, and language * Operating system and device information * Pages visited, referring URLs, and time spent * Clicks, scrolls, and other interaction events * Error and diagnostic logs ### API and Service Usage Data [Section titled “API and Service Usage Data”](#api-and-service-usage-data) For paid subscribers, we collect operational metadata required to deliver the Services: * API request timestamps, endpoints, and parameters * Request volumes, rate limits, and response codes * Account and session identifiers * Integration identifiers (e.g., MCP client or SDK version) We do not monitor, track, or retain the financial decisions, trades, or investment strategies you develop using our data. ## How We Use Your Information [Section titled “How We Use Your Information”](#how-we-use-your-information) We use the information we collect to: ### Provide the Services [Section titled “Provide the Services”](#provide-the-services) * Authenticate accounts and API requests * Deliver subscribed data, features, and integrations * Process subscriptions, payments, renewals, and refunds * Provide customer support and respond to inquiries ### Operate and Improve the Services [Section titled “Operate and Improve the Services”](#operate-and-improve-the-services) * Analyze usage patterns and performance * Diagnose and resolve technical issues * Develop new features, datasets, and integrations * Detect, prevent, and respond to fraud, abuse, or security threats ### Communicate With You [Section titled “Communicate With You”](#communicate-with-you) * Send transactional communications (account, billing, service notices) * Notify you of material changes to our terms, policies, or Services * Send marketing communications where permitted, with an option to unsubscribe * Respond to your questions and support requests ### Comply With Legal Obligations [Section titled “Comply With Legal Obligations”](#comply-with-legal-obligations) * Meet tax, accounting, and regulatory requirements * Respond to lawful requests from courts, regulators, or law enforcement * Enforce our Terms and protect our rights, property, and users ## Cookies and Similar Technologies [Section titled “Cookies and Similar Technologies”](#cookies-and-similar-technologies) We use cookies, local storage, and similar technologies to: * Keep you signed in and maintain session state * Remember preferences and settings * Measure traffic and improve the Services via analytics providers * Support security and fraud prevention You can control cookies through your browser settings. Disabling cookies may impair certain features of the Services. ## How We Share Information [Section titled “How We Share Information”](#how-we-share-information) We do not sell, rent, or trade your personal information. We share information only in the limited circumstances described below. ### Service Providers [Section titled “Service Providers”](#service-providers) We engage trusted third-party providers to help operate the Services. These include: * **Payment processing** (e.g., Stripe) * **Cloud infrastructure and hosting** * **Analytics and product telemetry** * **Email and transactional communications** * **Customer support tooling** These providers access information only to perform services on our behalf and are contractually obligated to protect it. ### Legal and Safety [Section titled “Legal and Safety”](#legal-and-safety) We may disclose information when we reasonably believe it is necessary to: * Comply with applicable law, regulation, legal process, or governmental request * Enforce our Terms and other agreements * Investigate or prevent fraud, security incidents, or abuse * Protect the rights, property, or safety of FinBrain, our users, or the public ### Business Transfers [Section titled “Business Transfers”](#business-transfers) If FinBrain is involved in a merger, acquisition, financing, reorganization, or sale of assets, your information may be transferred as part of that transaction, subject to the terms of this Privacy Policy. ### With Your Consent [Section titled “With Your Consent”](#with-your-consent) We may share information with other parties when you direct or authorize us to do so (for example, connecting a third-party application to your account). ## Data Security [Section titled “Data Security”](#data-security) We implement administrative, technical, and physical safeguards designed to protect your information, including: * Encryption of data in transit (TLS) * Access controls, authentication, and least-privilege principles * Monitoring, logging, and incident response procedures * Regular review of security practices No method of transmission or storage is 100% secure. We cannot guarantee absolute security, and you are responsible for keeping your account credentials confidential. ## Data Retention [Section titled “Data Retention”](#data-retention) We retain information for as long as necessary to provide the Services, operate our business, and comply with legal obligations. Specifically: * Account and billing information: retained while your account is active and for a reasonable period thereafter * API and usage logs: typically retained for up to 90 days for debugging, security, and abuse prevention * Records required for tax, accounting, or legal compliance: retained for the period required by applicable law You may request deletion of your account and associated data at any time, subject to our legal and operational retention obligations. ## Your Rights [Section titled “Your Rights”](#your-rights) Depending on your jurisdiction, you may have rights regarding your personal information, including the right to: * Access the personal information we hold about you * Request correction of inaccurate or incomplete information * Request deletion of your personal information (“right to be forgotten”) * Receive a portable copy of your information * Restrict or object to certain processing * Withdraw consent where processing is based on consent * Opt out of marketing communications To exercise any of these rights, contact us at . We may need to verify your identity before acting on a request. We will respond within the timeframe required by applicable law. If you are in the European Economic Area, United Kingdom, or Switzerland, you have the right to lodge a complaint with your local supervisory authority. ## International Data Transfers [Section titled “International Data Transfers”](#international-data-transfers) FinBrain is based in the United States, and your information may be processed in the U.S. and other countries where we or our service providers operate. Where required, we rely on appropriate legal mechanisms (such as Standard Contractual Clauses) to protect international transfers. ## Children’s Privacy [Section titled “Children’s Privacy”](#childrens-privacy) The Services are not directed to children under 18, and we do not knowingly collect personal information from anyone under 18. If we learn that we have collected such information, we will delete it promptly. Parents or guardians who believe a minor has provided us with information should contact us at . ## Third-Party Links and Integrations [Section titled “Third-Party Links and Integrations”](#third-party-links-and-integrations) The Services may contain links to third-party websites or allow integration with third-party applications (including large language models and AI assistants). This Privacy Policy does not apply to those third parties. We encourage you to review their privacy policies before providing any information. ## Changes to This Privacy Policy [Section titled “Changes to This Privacy Policy”](#changes-to-this-privacy-policy) We may update this Privacy Policy from time to time. When we do, we will: * Post the updated policy on our website * Update the “Last updated” date * Where appropriate, notify you by email or through the Services Your continued use of the Services after the effective date of a revised policy constitutes acceptance of the changes. ## Contact Us [Section titled “Contact Us”](#contact-us) For questions, requests, or concerns regarding this Privacy Policy or our data practices: **Email:** **Website:** [finbrain.tech](https://finbrain.tech) ## Compliance [Section titled “Compliance”](#compliance) We strive to comply with applicable privacy laws, including: * General Data Protection Regulation (GDPR) * UK Data Protection Act and UK GDPR * California Consumer Privacy Act (CCPA) and California Privacy Rights Act (CPRA) * Other applicable U.S. state and international privacy regulations *** *Last updated: April 18, 2026* # Dashboard > Real-time market command center with price forecast signals, geopolitical monitoring, earnings calendar, treasury yields, and social sentiment widgets. The Dashboard is the Terminal’s landing page — a real-time command center that surfaces the most important market signals across all asset classes in a single view. It is designed to give you a comprehensive snapshot of market conditions the moment you log in. ![FinBrain Terminal Dashboard](/_astro/terminal-dashboard.fWJwmCTb.png) ## Ticker Tape [Section titled “Ticker Tape”](#ticker-tape) A live scrolling ticker strip runs across the top of the Dashboard, displaying real-time prices and percentage changes for major indices (S\&P 500, NASDAQ, DOW) and widely followed stocks and crypto assets. This provides an at-a-glance market pulse without navigating away from the Dashboard. ## Geopolitical Globe [Section titled “Geopolitical Globe”](#geopolitical-globe) An interactive 3D globe visualizes global events in real time. Events are sourced from six specialized databases: | Source | Coverage | | ------ | -------------------------------------------------- | | ACLED | Armed conflict location and event data | | UCDP | Uppsala Conflict Data Program | | GDELT | Global Database of Events, Language, and Tone | | HAPI | Humanitarian Data Exchange | | USGS | Geological events (earthquakes, volcanic activity) | | EONET | NASA Earth Observatory natural event tracking | The globe also includes an INFORM national risk layer as the base visualization. Click any event marker for details. The Dashboard shows a compact version of the globe — the full-width version with regional presets is available on the [Intelligence](/terminal/intelligence/) page. ## Activity Wire [Section titled “Activity Wire”](#activity-wire) A unified real-time feed that combines four types of market-moving activity into a single stream: * **Insider Trading** — SEC Form 4 filings showing executive purchases and sales * **Congressional Trading** — House and Senate member stock transactions * **Corporate Lobbying** — Lobbying disclosure filings and expenditures * **Government Contracts** — Federal contract awards from USAspending.gov Each entry shows a type badge, ticker link, actor name, transaction details, dollar value, and time elapsed. Filter by activity type to focus on specific signals. ## Earnings Calendar [Section titled “Earnings Calendar”](#earnings-calendar) Upcoming earnings reports for the current and next week. Each entry includes: | Column | Description | | ------------- | ------------------------------------------- | | Date | Earnings report date | | Ticker | Company symbol (clickable to Ticker Page) | | Company | Full company name | | EPS Forecast | Consensus expected earnings per share | | Last Year EPS | Same-quarter EPS from the prior year | | Timing | Pre-market, after-hours, or regular session | The calendar helps you anticipate volatility around earnings announcements. ## Top AI Signals [Section titled “Top AI Signals”](#top-ai-signals) The strongest bullish and bearish price forecasts, displayed in two columns: * **Bullish** — Top 7 tickers with the highest predicted positive returns * **Bearish** — Top 7 tickers with the highest predicted negative returns Each entry shows the ticker, company name, and predicted 10-day return percentage. Use the market dropdown to filter by index (S\&P 500, NASDAQ, DOW 30, etc.). A summary bar shows the overall market distribution: how many tickers are bullish, neutral, or bearish. For deeper analysis on any signal, click through to the [Ticker Page](/terminal/ticker-page/) or explore the [Price Forecasts Dataset](/datasets/ai-forecasts/). ## Treasury Yield Curve [Section titled “Treasury Yield Curve”](#treasury-yield-curve) A line chart displaying US Treasury par yields across maturities from 1 month to 30 years. The curve shape provides a real-time read on rate expectations: * **Normal curve** (upward sloping) — longer maturities yield more, indicating economic expansion expectations * **Inverted curve** (downward sloping) — short-term rates exceed long-term, historically preceding recessions The widget includes automatic inversion detection. For more detailed fixed income analysis, see the [Fixed Income](/terminal/markets/fixed-income/) page. ## Recent News [Section titled “Recent News”](#recent-news) The latest financial headlines with AI-generated sentiment scores. Each article displays: | Column | Description | | --------- | ----------------------------------- | | Ticker | Associated stock symbol | | Company | Company name | | Date | Publication date | | Headline | Article title (clickable to source) | | Source | News outlet | | Sentiment | AI sentiment score (-1 to +1) | A summary bar shows total article count, unique tickers covered, average sentiment, and sentiment trend direction. Articles are deduplicated across sources. ## Quick Ticker Lookup [Section titled “Quick Ticker Lookup”](#quick-ticker-lookup) A search box for rapidly checking any ticker without navigating to its full Ticker Page. Enter a symbol to see: * **Mini price chart** — 1-month price history * **5-day price forecast** — Direction and expected return percentage * **Sentiment snapshot** — Current average sentiment score with label This is useful for quick checks during research. For full analysis, click through to the [Ticker Page](/terminal/ticker-page/). ## Reddit Mentions [Section titled “Reddit Mentions”](#reddit-mentions) A stacked bar chart showing the top 15 most-mentioned tickers across investing subreddits. Tracked communities include: * wallstreetbets, stocks, investing, options * pennystocks, stockmarket, daytrading, valueinvesting The chart breaks down mention volume by subreddit, making it easy to see which communities are driving attention. For individual ticker Reddit data, see the [Reddit Mentions Dataset](/datasets/reddit-mentions/). ## Crypto Overview [Section titled “Crypto Overview”](#crypto-overview) A summary card showing cryptocurrency market metrics: * **Total market cap** — Combined value of all cryptocurrencies * **24h change** — Market-wide percentage change * **BTC dominance** — Bitcoin’s share of total crypto market cap * **24h volume** — Total trading volume across exchanges For deeper crypto analysis, see the [Crypto](/terminal/markets/crypto/) page. ## US Fiscal Dashboard [Section titled “US Fiscal Dashboard”](#us-fiscal-dashboard) Key US government fiscal indicators: * **National debt** — Total outstanding federal debt * **Public debt** — Debt held by the public (excluding intragovernmental) * **Monthly deficit** — Current month’s budget shortfall or surplus * **FYTD deficit** — Fiscal year-to-date cumulative deficit For more fiscal and fixed income data, see the [Fixed Income](/terminal/markets/fixed-income/) page. ## Related Resources [Section titled “Related Resources”](#related-resources) * [Intelligence](/terminal/intelligence/) — Geopolitical monitoring and COT positioning * [Markets Hub](/terminal/markets/overview/) — Asset class dashboards * [Ticker Page](/terminal/ticker-page/) — Individual stock analysis * [Screeners](/terminal/screeners/) — Filter stocks by alternative data # Intelligence > Geopolitical monitoring and macro analysis with an interactive conflict globe, defense and OSINT feeds, and CFTC Commitments of Traders positioning data. The Intelligence page provides geopolitical and macro-level analysis tools for monitoring global risk and institutional positioning. It consolidates conflict data, open-source intelligence, and futures positioning into a single view. ![FinBrain Terminal Intelligence](/_astro/terminal-intelligence.CwYov_Bi.png) ## Geopolitical Globe [Section titled “Geopolitical Globe”](#geopolitical-globe) A full-width interactive 3D globe (also available in compact form on the [Dashboard](/terminal/dashboard/)) that visualizes global events in real time. Events are plotted as markers on the globe, color-coded by type and severity. ### Data Sources [Section titled “Data Sources”](#data-sources) | Source | Coverage | | ------ | -------------------------------------------------- | | ACLED | Armed conflict location and event data | | UCDP | Uppsala Conflict Data Program | | GDELT | Global Database of Events, Language, and Tone | | HAPI | Humanitarian Data Exchange | | USGS | Geological events (earthquakes, volcanic activity) | | EONET | NASA Earth Observatory natural event tracking | | INFORM | National risk index (base layer) | ### Regional Presets [Section titled “Regional Presets”](#regional-presets) Jump directly to areas of interest using the regional preset buttons: | Preset | Focus Area | | ---------------- | ----------------------------------- | | Global | Full world view | | Strait of Hormuz | Persian Gulf oil transit chokepoint | | South China Sea | Maritime territorial disputes | | Europe | European theater | | Middle East | Middle Eastern conflicts and events | Click any event marker on the globe to view details including event type, date, source, and description. Zoom and rotate the globe to explore specific regions. ## Intel Feed [Section titled “Intel Feed”](#intel-feed) Aggregated defense, OSINT, and geopolitical analysis from six curated sources: | Source | Focus | | ---------------- | ------------------------------------------------ | | War on the Rocks | Defense policy and military strategy analysis | | Bellingcat | Open-source investigations and digital forensics | | Atlantic Council | Geopolitics, international security, and policy | | Foreign Affairs | International relations and global strategy | | CSIS | Center for Strategic and International Studies | | Breaking Defense | Defense industry news and procurement | Each article displays a color-coded source badge, title, description, and publication time with an external link to the full article. ### Filtering [Section titled “Filtering”](#filtering) Filter the feed by category: * **All** — All sources combined * **Defense** — Military strategy, procurement, and policy * **OSINT** — Open-source investigations and digital forensics * **Geopolitics** — International relations and security analysis ## COT Positioning [Section titled “COT Positioning”](#cot-positioning) CFTC Commitments of Traders (COT) data showing institutional and speculative positioning in futures markets. This weekly report reveals how different market participants are positioned. ### Asset Groups [Section titled “Asset Groups”](#asset-groups) | Group | Examples | | ----------- | ------------------------------------------------- | | Indices | S\&P 500, NASDAQ, Dow Jones, Russell 2000 futures | | Energy | Crude oil, natural gas, gasoline futures | | Metals | Gold, silver, copper, platinum futures | | Forex | EUR, GBP, JPY, CHF, AUD, CAD futures | | Agriculture | Corn, wheat, soybeans, cotton, sugar futures | | Bonds | Treasury bonds, notes, Eurodollar futures | ### Table Columns [Section titled “Table Columns”](#table-columns) | Column | Description | | -------------- | ------------------------------------------------- | | Contract | Futures contract name | | Open Interest | Total outstanding contracts | | Speculator Net | Net position of large speculators (managed money) | | Commercial Net | Net position of commercial hedgers | | Retail Net | Net position of non-reportable (retail) traders | | WoW Change | Week-over-week change in speculator positioning | | Spec Bias | Visual bar showing bullish/bearish lean | ### Reading COT Data [Section titled “Reading COT Data”](#reading-cot-data) * **Speculator net long** (green) — Managed money is bullish on the asset * **Speculator net short** (red) — Managed money is bearish * **Extreme positioning** — When speculator positions reach historical extremes, it can signal potential reversals * **Commercial vs speculator divergence** — When commercials (hedgers) and speculators take opposite sides, it often precedes directional moves The COT report is published weekly by the CFTC and covers regulated futures markets. For commodity-specific COT data, see [Commodities](/terminal/markets/commodities/). For FX-specific positioning, see [Currencies](/terminal/markets/currencies/). ## Related Resources [Section titled “Related Resources”](#related-resources) * [Dashboard](/terminal/dashboard/) — Real-time market command center * [Fixed Income](/terminal/markets/fixed-income/) — Treasury yields and central bank rates * [Commodities](/terminal/markets/commodities/) — Energy charts and commodity COT * [Currencies](/terminal/markets/currencies/) — FX rates and currency COT # Commodities > Energy, metals, and agriculture market data with EIA inventory charts, CFTC Commitments of Traders positioning, and commodity futures analysis. The Commodities page covers energy, metals, and agriculture markets with EIA supply data and CFTC institutional positioning. These tools help monitor supply/demand fundamentals alongside how institutional traders are positioned in commodity futures. ![FinBrain Terminal Commodities](/_astro/terminal-commodities.BeJPQLTd.png) ## Market Navigation [Section titled “Market Navigation”](#market-navigation) The page links to dedicated market screener pages for: * **Commodities** — Energy, metals, and agricultural commodity tickers with price forecasts and sentiment * **Index Futures** — Major index futures contracts Click through to browse all available tickers with full prediction and alternative data coverage. ## EIA Energy Charts [Section titled “EIA Energy Charts”](#eia-energy-charts) Four interactive time-series charts sourced from the US Energy Information Administration (EIA), updated weekly: ### Crude Oil Inventories [Section titled “Crude Oil Inventories”](#crude-oil-inventories) US commercial crude oil stocks excluding the Strategic Petroleum Reserve. Rising inventories generally indicate weaker demand or increased production, while falling inventories suggest tighter supply. ### US Oil Production [Section titled “US Oil Production”](#us-oil-production) Domestic crude oil production volume. Tracks production trends that affect global supply and pricing dynamics. ### Natural Gas Storage [Section titled “Natural Gas Storage”](#natural-gas-storage) US natural gas working storage volumes. Storage levels relative to the five-year average are a key driver of natural gas pricing, especially heading into winter heating season. ### Gasoline Inventories [Section titled “Gasoline Inventories”](#gasoline-inventories) US motor gasoline stocks. Seasonal patterns are significant — inventories typically draw down heading into summer driving season and build during fall. Each chart displays the data as a colored line chart with time on the x-axis and volume/production on the y-axis. ## Commodity COT Positioning [Section titled “Commodity COT Positioning”](#commodity-cot-positioning) CFTC Commitments of Traders data specific to commodity futures, organized by category: ### Categories [Section titled “Categories”](#categories) | Category | Examples | | ----------- | ----------------------------------------------------------- | | Energy | Crude oil, natural gas, heating oil, gasoline futures | | Metals | Gold, silver, copper, platinum, palladium futures | | Agriculture | Corn, wheat, soybeans, cotton, sugar, coffee, cocoa futures | ### Table Columns [Section titled “Table Columns”](#table-columns) | Column | Description | | -------------- | --------------------------------------------------------- | | Contract | Futures contract name | | Open Interest | Total outstanding contracts | | Speculator Net | Net position of managed money | | Commercial Net | Net position of commercial hedgers (producers, consumers) | | WoW Change | Week-over-week change in speculator positioning | | Spec Bias | Visual bar showing bullish/bearish lean | ### Reading Commodity COT [Section titled “Reading Commodity COT”](#reading-commodity-cot) * **Commercial hedgers** in commodities are often producers or consumers with physical exposure — their positioning reflects business hedging needs * **Speculator extremes** in commodity futures can signal crowded trades — historically, extreme long or short positioning tends to precede reversals * **WoW changes** reveal the pace of positioning shifts — rapid changes in a single week often indicate a catalyst For the full COT dataset across all asset classes (including indices, forex, and bonds), see the [Intelligence](/terminal/intelligence/) page. ## Related Resources [Section titled “Related Resources”](#related-resources) * [Intelligence](/terminal/intelligence/) — Full COT positioning across all asset classes * [Currencies](/terminal/markets/currencies/) — FX COT positioning * [Markets Hub](/terminal/markets/overview/) — All asset class dashboards # Crypto > Cryptocurrency market overview with top coins by market cap, Fear and Greed index, Bitcoin network stats, CME futures positioning, trending coins, and crypto news with sentiment. The Crypto page provides a comprehensive view of cryptocurrency markets, combining price data, sentiment indicators, on-chain fundamentals, institutional positioning, and trend signals. ![FinBrain Terminal Crypto](/_astro/terminal-crypto.DhArRFZ7.png) ## Global Statistics [Section titled “Global Statistics”](#global-statistics) A four-column summary of cryptocurrency market conditions: | Metric | Description | | ---------------- | ---------------------------------------------------------- | | Total Market Cap | Combined value of all tracked cryptocurrencies | | 24h Volume | Total trading volume across exchanges in the last 24 hours | | BTC Dominance | Bitcoin’s percentage share of total crypto market cap | | Active Cryptos | Number of actively traded cryptocurrencies | These headline metrics provide an instant read on the overall crypto market state. ## Top Coins [Section titled “Top Coins”](#top-coins) The top 20 cryptocurrencies ranked by market capitalization. Each entry includes: | Column | Description | | ------------ | -------------------------------------- | | Rank | Market cap ranking | | Name | Cryptocurrency name | | Symbol | Ticker symbol | | Price | Current price in USD | | 24h Change | Percentage change in the last 24 hours | | 7d Change | Percentage change over the last 7 days | | Market Cap | Total market capitalization | | 7d Sparkline | Mini chart showing 7-day price trend | Click any coin to navigate to its Ticker Page for detailed analysis with price forecasts and sentiment data. ## Crypto News [Section titled “Crypto News”](#crypto-news) The latest cryptocurrency headlines with AI-generated sentiment scores. Each article displays the headline, source, publication time, and a sentiment score from -1 (bearish) to +1 (bullish). ## Fear and Greed Index [Section titled “Fear and Greed Index”](#fear-and-greed-index) A gauge-style visualization of the crypto market sentiment index, measuring overall market emotion on a scale of 0 to 100: | Range | Label | Interpretation | | ------ | ------------- | ------------------------------------------------------------------ | | 0-24 | Extreme Fear | Markets are very fearful — historically a contrarian buying signal | | 25-49 | Fear | Below-average sentiment, caution prevails | | 50 | Neutral | Balanced market sentiment | | 51-74 | Greed | Above-average optimism, increased risk appetite | | 75-100 | Extreme Greed | Markets are euphoric — historically a contrarian selling signal | A 14-day trend line shows how sentiment has evolved recently, helping distinguish between a temporary spike and a sustained shift in market emotion. ## Bitcoin Network Stats [Section titled “Bitcoin Network Stats”](#bitcoin-network-stats) On-chain fundamentals for the Bitcoin network: | Metric | Description | | -------------- | -------------------------------------------------------------------------- | | Hashrate | Total computational power securing the network (EH/s) | | Difficulty | Current mining difficulty level | | Epoch Progress | Percentage progress toward the next difficulty adjustment (\~2,016 blocks) | A 30-day hashrate chart shows the trend in mining computational power. Rising hashrate generally indicates growing miner confidence and network security, while declining hashrate may signal miner capitulation or external pressures. ## Trending Coins [Section titled “Trending Coins”](#trending-coins) The top 8 trending cryptocurrencies on CoinGecko, based on user search volume over the past 24 hours. This surface shows which coins are generating the most attention regardless of their market cap ranking — useful for identifying emerging narratives before they’re reflected in prices. ## CME Bitcoin Futures Positioning [Section titled “CME Bitcoin Futures Positioning”](#cme-bitcoin-futures-positioning) CFTC Commitments of Traders data for CME Bitcoin futures, showing institutional positioning in the regulated US futures market: | Column | Description | | -------------- | ------------------------------------------------- | | Open Interest | Total outstanding CME Bitcoin futures contracts | | Speculator Net | Net position of managed money (hedge funds, CTAs) | | Commercial Net | Net position of commercial participants | | WoW Change | Week-over-week change in positioning | | Spec Bias | Visual indicator of bullish/bearish lean | CME Bitcoin futures attract institutional traders who may not participate in spot crypto exchanges. Their positioning provides a regulated, transparent view of institutional sentiment toward Bitcoin. For the full COT dataset across all asset classes, see the [Intelligence](/terminal/intelligence/) page. ## Related Resources [Section titled “Related Resources”](#related-resources) * [Dashboard](/terminal/dashboard/) — Crypto overview widget * [Intelligence](/terminal/intelligence/) — Full COT positioning across all asset classes * [Markets Hub](/terminal/markets/overview/) — All asset class dashboards # Currencies > Foreign exchange rates from the Federal Reserve and ECB, CFTC currency futures positioning, and FX news aggregation with central bank source tracking. The Currencies page provides foreign exchange rate data from official central bank sources, institutional positioning in currency futures, and a curated FX news feed with central bank source identification. ![FinBrain Terminal Currencies](/_astro/terminal-currencies.DTKHS4Di.png) ## Market Navigation [Section titled “Market Navigation”](#market-navigation) The page links to the **Foreign Exchange** market screener page, where you can browse all available FX pairs with price forecasts and sentiment data. ## Fed FX Rates [Section titled “Fed FX Rates”](#fed-fx-rates) Official exchange rates from the Federal Reserve’s H.10 statistical release. The H.10 provides daily noon buying rates for major currencies against the US dollar. Each currency pair displays: * **Current rate** — Latest exchange rate (4-decimal precision) * **30-day sparkline** — Mini trend chart showing the rate’s recent trajectory This table covers all currencies published in the Fed’s H.10 release, providing a comprehensive view of USD exchange rates from an official source. ## ECB FX Rates [Section titled “ECB FX Rates”](#ecb-fx-rates) European Central Bank EUR reference rates, providing official exchange rates denominated in euros rather than US dollars. Each pair includes a 30-day sparkline for trend context. Comparing the Fed and ECB rate tables side-by-side shows the same currencies from two different base currency perspectives — useful for identifying relative strength/weakness patterns. ## FX COT Positioning [Section titled “FX COT Positioning”](#fx-cot-positioning) CFTC Commitments of Traders data for currency futures, showing how institutional and speculative traders are positioned in major currency pairs. | Column | Description | | -------------- | ----------------------------------------------- | | Contract | Currency futures contract (e.g., EUR, GBP, JPY) | | Open Interest | Total outstanding contracts | | Speculator Net | Net position of managed money | | Commercial Net | Net position of commercial hedgers | | WoW Change | Week-over-week change in speculator positioning | | Spec Bias | Visual bar showing bullish/bearish lean | ### Reading FX COT [Section titled “Reading FX COT”](#reading-fx-cot) * **Net long** in a currency future means speculators expect that currency to appreciate against USD * **Net short** means speculators expect depreciation * **Extreme speculator positioning** in FX futures has historically correlated with currency turning points * **Divergence from commercial positioning** often signals that speculative momentum is overextended For the full COT dataset across all asset classes, see the [Intelligence](/terminal/intelligence/) page. ## FX News Feed [Section titled “FX News Feed”](#fx-news-feed) An aggregated news feed from five sources, each color-coded for quick identification: | Source | Color | Focus | | --------------- | ------ | ------------------------------------------ | | FXStreet | Blue | FX market analysis and commentary | | Federal Reserve | Green | Fed statements, minutes, speeches | | ECB | Purple | ECB policy decisions and commentary | | BOJ | Red | Bank of Japan monetary policy updates | | BIS | Orange | Bank for International Settlements reports | The color coding makes it easy to scan the feed for central bank communications versus market analysis. This is particularly useful around policy meeting dates when central bank headlines drive FX volatility. ## Related Resources [Section titled “Related Resources”](#related-resources) * [Fixed Income](/terminal/markets/fixed-income/) — Central bank policy rates and yield curves * [Intelligence](/terminal/intelligence/) — Full COT positioning across all asset classes * [Markets Hub](/terminal/markets/overview/) — All asset class dashboards # Equities > Global equity market data across US, Americas, Asia-Pacific, European, and Middle Eastern exchanges with AI signals, analyst ratings, earnings and IPO calendars, and alternative data feeds. The Equities page provides a comprehensive view of global equity markets with regional organization, AI-generated signals, and alternative data feeds. Click any market to open its dedicated screener page with all available tickers. ## Market Coverage [Section titled “Market Coverage”](#market-coverage) ### United States [Section titled “United States”](#united-states) | Market | Description | | ---------- | -------------------------------------- | | S\&P 500 | 500 largest US companies by market cap | | NASDAQ | Technology-heavy exchange listings | | NYSE | New York Stock Exchange listings | | DOW 30 | 30 blue-chip industrial stocks | | ETFs | Exchange-traded funds | | OTC Market | Over-the-counter securities | ### Americas [Section titled “Americas”](#americas) | Market | Description | | -------------- | ------------------------- | | Canada TSX | Toronto Stock Exchange | | Brazil BOVESPA | B3 (Brasil Bolsa Balcao) | | Mexico BMV | Bolsa Mexicana de Valores | ### Asia-Pacific [Section titled “Asia-Pacific”](#asia-pacific) | Market | Description | | ------------- | ------------------------------ | | HK Hang Seng | Hong Kong Stock Exchange | | Australia ASX | Australian Securities Exchange | | Russia MOEX | Moscow Exchange | ### Europe [Section titled “Europe”](#europe) | Market | Description | | ----------- | ---------------------------------- | | UK FTSE 100 | Financial Times Stock Exchange 100 | | Germany DAX | Deutscher Aktienindex | ### Middle East [Section titled “Middle East”](#middle-east) | Market | Description | | ------------- | ----------------------- | | Tadawul TASI | Saudi Stock Exchange | | Tel Aviv TASE | Tel Aviv Stock Exchange | Each market card shows the ticker count and links to a dedicated market screener page where you can browse all tickers with price forecasts, sentiment, and trading activity data. ## Top AI Signals [Section titled “Top AI Signals”](#top-ai-signals) The strongest bullish and bearish price forecasts across equities. This widget shows the top 7 tickers in each direction with their predicted 10-day returns. Use the market dropdown to filter by specific index or exchange. A summary bar displays the overall market distribution — how many tickers are bullish, neutral, or bearish. For detailed prediction data, see the [Price Forecasts Dataset](/datasets/ai-forecasts/). ## Activity Wire [Section titled “Activity Wire”](#activity-wire) A unified feed combining four types of market-moving corporate and political activity: * **Insider Trading** — SEC Form 4 filings from corporate executives * **Congressional Trading** — Stock transactions by US House and Senate members * **Corporate Lobbying** — Lobbying disclosure filings * **Government Contracts** — Federal contract awards Each entry links to the relevant ticker for deeper analysis. ## Recent Analyst Ratings [Section titled “Recent Analyst Ratings”](#recent-analyst-ratings) The latest analyst upgrades, downgrades, initiations, and reiterations. Each rating shows: | Column | Description | | ------------ | ------------------------------------------- | | Date | Rating publication date | | Ticker | Company symbol (clickable) | | Institution | Analyst firm name | | Action | Upgraded, Downgraded, Initiated, Reiterated | | Rating | Buy, Overweight, Hold, Underweight, Sell | | Target Price | Price target (if provided) | For individual ticker ratings, see the [Ticker Page](/terminal/ticker-page/). For the full dataset, see [Analyst Ratings](/datasets/analyst-ratings/). ## Recent News Feed [Section titled “Recent News Feed”](#recent-news-feed) Latest equity market headlines with AI-generated sentiment scores. Articles are sourced from major financial news outlets and scored on a scale from -1 (bearish) to +1 (bullish). ## Earnings Calendar [Section titled “Earnings Calendar”](#earnings-calendar) Upcoming earnings reports with expected and prior-year EPS. The calendar covers the current and following week, with entries tagged by timing (pre-market, after-hours, or regular session). ## IPO Calendar [Section titled “IPO Calendar”](#ipo-calendar) Upcoming and recently completed initial public offerings. Each entry includes the company name, expected ticker, exchange, pricing date, and anticipated price range. ## Related Resources [Section titled “Related Resources”](#related-resources) * [Markets Hub](/terminal/markets/overview/) — All asset class dashboards * [Ticker Page](/terminal/ticker-page/) — Individual stock analysis * [Screeners](/terminal/screeners/) — Filter stocks by alternative data * [Price Forecasts Dataset](/datasets/ai-forecasts/) — Prediction methodology and coverage # Fixed Income > Treasury yield curves, central bank policy rates, interbank rates, systemic stress indicators, and US fiscal metrics for fixed income analysis. The Fixed Income page provides tools for yield curve analysis, central bank rate monitoring, credit stress tracking, and US fiscal data. These indicators are essential for understanding interest rate environments, credit conditions, and sovereign risk. ![FinBrain Terminal Fixed Income](/_astro/terminal-fixed-income.6PVfrKJ2.png) ## US Treasury Yield Curve [Section titled “US Treasury Yield Curve”](#us-treasury-yield-curve) An interactive line chart displaying US Treasury par yields across the full maturity spectrum: **Maturities covered:** 1 month, 3 months, 6 months, 1 year, 2 years, 3 years, 5 years, 7 years, 10 years, 20 years, 30 years ### Curve Interpretation [Section titled “Curve Interpretation”](#curve-interpretation) | Shape | Meaning | | --------------------------- | ------------------------------------------------------------------------------------ | | Normal (upward sloping) | Longer maturities yield more than shorter — indicates market expects economic growth | | Flat | Similar yields across maturities — transition period, uncertainty about direction | | Inverted (downward sloping) | Short-term rates exceed long-term — historically precedes recessions | The widget includes automatic inversion detection, highlighting when the curve inverts. A compact version of this chart also appears on the [Dashboard](/terminal/dashboard/). ## EUR Yield Curve [Section titled “EUR Yield Curve”](#eur-yield-curve) AAA-rated European sovereign bond yields from the ECB, providing a comparable view of European rate expectations. This curve covers EUR government bonds with the highest credit quality. Like the US curve, this widget includes inversion detection. Comparing the US and EUR curves side-by-side reveals divergences in monetary policy expectations across the Atlantic. ## Central Bank Policy Rates [Section titled “Central Bank Policy Rates”](#central-bank-policy-rates) A table of official policy rates from 12 major central banks, sourced from the Bank for International Settlements (BIS): | Column | Description | | -------------- | ----------------------------------------------------- | | Central Bank | Institution name and country | | Current Rate | Current policy rate percentage | | Last Change | Direction and magnitude of the most recent adjustment | | Effective Date | Date the current rate became effective | This provides a single view of the global rate environment without needing to check each central bank individually. ## Interbank Rates [Section titled “Interbank Rates”](#interbank-rates) Short-term funding rates that reflect conditions in the interbank lending market: ### Rates Covered [Section titled “Rates Covered”](#rates-covered) * **EURIBOR** — Euro Interbank Offered Rate across multiple tenors * **ESTR** — Euro Short-Term Rate (ECB overnight reference rate) Each rate includes a 30-day trend sparkline showing recent movement. A summary grid highlights the four key rates with their current values. The ESTR history chart displays the overnight rate over time, providing context for ECB policy transmission into money markets. ## Systemic Stress Index [Section titled “Systemic Stress Index”](#systemic-stress-index) The ECB Composite Indicator of Systemic Stress (CISS) with a 52-week history chart. The CISS measures stress across five financial market segments: money market, bond market, equity market, FX market, and financial intermediaries. ### Reading the Stress Index [Section titled “Reading the Stress Index”](#reading-the-stress-index) | Level | Interpretation | | ------------------ | ----------------------------------------------------------- | | Low (near 0) | Calm market conditions, low systemic risk | | Moderate (0.2-0.4) | Elevated stress in one or more segments | | High (above 0.4) | Significant systemic stress across multiple market segments | The gauge visualization shows the current reading, while the area chart provides historical context to assess whether stress is building or subsiding. ## US Fiscal Dashboard [Section titled “US Fiscal Dashboard”](#us-fiscal-dashboard) Key US government fiscal indicators presented in a 2x2 metrics grid: | Metric | Description | | --------------- | -------------------------------------------------------------- | | National Debt | Total outstanding federal debt | | Public Debt | Debt held by the public (excluding intragovernmental holdings) | | Monthly Deficit | Current month’s budget shortfall or surplus | | FYTD Deficit | Fiscal year-to-date cumulative deficit | An additional breakdown shows the effective interest rate on federal debt, providing context for the government’s borrowing costs relative to the yield curve. ## Related Resources [Section titled “Related Resources”](#related-resources) * [Dashboard](/terminal/dashboard/) — Treasury yield curve widget * [Intelligence](/terminal/intelligence/) — COT positioning for bond futures * [Markets Hub](/terminal/markets/overview/) — All asset class dashboards # Markets Hub > Navigate FinBrain Terminal's market coverage across equities, fixed income, commodities, currencies, and crypto with dedicated dashboards for each asset class. The Markets Hub is the gateway to five asset-class-specific dashboards. Each dashboard provides specialized widgets, data sources, and market context tailored to that asset class. ## Equities [Section titled “Equities”](#equities) Global equity market coverage spanning 16 exchanges across five regions. The Equities dashboard includes price forecast signals, an activity wire for insider and congressional trades, recent analyst ratings, earnings and IPO calendars, and market-specific news. **Coverage:** S\&P 500, NASDAQ, NYSE, DOW 30, ETFs, OTC, TSX, BOVESPA, BMV, Hang Seng, ASX, MOEX, FTSE 100, DAX, TASI, TASE [Go to Equities →](/terminal/markets/equities/) ## Fixed Income [Section titled “Fixed Income”](#fixed-income) Treasury yield curve analysis, central bank rate monitoring, and credit stress tracking. The Fixed Income dashboard covers US and European sovereign yields, BIS policy rates for 12 central banks, interbank funding rates, the ECB systemic stress index, and US fiscal indicators. [Go to Fixed Income →](/terminal/markets/fixed-income/) ## Commodities [Section titled “Commodities”](#commodities) Energy, metals, and agriculture market data. The Commodities dashboard features EIA inventory and production charts for crude oil, natural gas, and gasoline, alongside CFTC Commitments of Traders positioning data for commodity futures. [Go to Commodities →](/terminal/markets/commodities/) ## Currencies [Section titled “Currencies”](#currencies) Foreign exchange rates, institutional positioning, and central bank news. The Currencies dashboard shows official Fed and ECB exchange rates with 30-day sparklines, CFTC currency futures positioning, and an FX news feed aggregating updates from the Fed, ECB, BOJ, BIS, and FXStreet. [Go to Currencies →](/terminal/markets/currencies/) ## Crypto [Section titled “Crypto”](#crypto) Cryptocurrency market data, sentiment, and network fundamentals. The Crypto dashboard covers top coins by market cap, the Fear and Greed index, Bitcoin network statistics (hashrate, difficulty), CoinGecko trending coins, crypto-specific news with sentiment, and CME Bitcoin futures positioning. [Go to Crypto →](/terminal/markets/crypto/) ## Related Resources [Section titled “Related Resources”](#related-resources) * [Dashboard](/terminal/dashboard/) — Real-time market command center * [Intelligence](/terminal/intelligence/) — Geopolitical monitoring and COT data * [Ticker Page](/terminal/ticker-page/) — Individual stock analysis # FinBrain Terminal Overview > Web-based platform for FinBrain's 12 alternative datasets, with real-time dashboards, geopolitical monitoring, price forecasts, alternative data screeners, and portfolio analytics across equities, fixed income, commodities, currencies, and crypto. The FinBrain Terminal is a web-based platform for exploring FinBrain’s 12 alternative datasets interactively. Monitor markets in real time, track geopolitical risk, screen stocks with alternative data, and manage portfolios — all without writing code. ## Access the Terminal [Section titled “Access the Terminal”](#access-the-terminal) Visit the FinBrain Terminal at: **[terminal.finbrain.tech](https://terminal.finbrain.tech)** ## Main Sections [Section titled “Main Sections”](#main-sections) The Terminal is organized into six main areas: ### Dashboard [Section titled “Dashboard”](#dashboard) ![FinBrain Terminal Dashboard](/_astro/terminal-dashboard.fWJwmCTb.png) Your command center for real-time market intelligence. The Dashboard surfaces the most important signals across all asset classes in a single view: * **Ticker tape** with live prices for major indices and stocks * **Geopolitical globe** monitoring global conflicts, events, and risk * **Activity wire** combining insider trades, congressional activity, lobbying, and government contracts * **Prediction markets** with real-money probabilities on geopolitical and economic events * **Top AI signals** showing the strongest bullish and bearish predictions * **Treasury yield curve**, crypto overview, and US fiscal indicators * **Earnings calendar**, recent news with sentiment, and Reddit mention rankings [Learn more about the Dashboard →](/terminal/dashboard/) ### Intelligence [Section titled “Intelligence”](#intelligence) ![FinBrain Terminal Intelligence](/_astro/terminal-intelligence.CwYov_Bi.png) Geopolitical monitoring and macro-level analysis for institutional decision-making: * **Interactive globe** with full-width visualization and regional presets (Strait of Hormuz, South China Sea, Europe, Middle East) * **Prediction markets** for tracking real-money probabilities * **Intel feed** aggregating defense and OSINT analysis from Bellingcat, CSIS, Atlantic Council, and more * **COT positioning** with CFTC Commitments of Traders data across indices, energy, metals, forex, agriculture, and bonds [Learn more about Intelligence →](/terminal/intelligence/) ### Markets [Section titled “Markets”](#markets) ![FinBrain Terminal Markets](/_astro/terminal-commodities.BeJPQLTd.png) Five dedicated dashboards for each major asset class, accessible from the Markets Hub: * **[Equities](/terminal/markets/equities/)** — 16 global exchanges across US, Americas, Asia-Pacific, Europe, and Middle East with AI signals, analyst ratings, earnings, and IPO calendars * **[Fixed Income](/terminal/markets/fixed-income/)** — US and EUR yield curves, central bank policy rates, interbank rates, systemic stress indicators, and fiscal metrics * **[Commodities](/terminal/markets/commodities/)** — EIA energy data (crude, natural gas, gasoline inventories) and CFTC commodity futures positioning * **[Currencies](/terminal/markets/currencies/)** — Federal Reserve and ECB exchange rates, FX futures positioning, and central bank news feeds * **[Crypto](/terminal/markets/crypto/)** — Market cap rankings, Fear and Greed index, Bitcoin network stats, trending coins, and CME futures positioning [Browse all Markets →](/terminal/markets/overview/) ### Ticker Page [Section titled “Ticker Page”](#ticker-page) ![FinBrain Terminal Ticker Page](/_astro/terminal-ticker.x_84Nb4g.png) Deep dive into individual stocks with comprehensive data across all available datasets: * **Interactive price chart** with technical indicators and drawing tools * **Price forecast charts** for daily (10-day) and monthly (12-month) predictions * **Alternative data visualizations** for sentiment, LinkedIn metrics, app ratings, put/call ratios, and Reddit mentions * **Data tables** for news, analyst ratings, insider transactions, congressional trades, corporate lobbying, and government contracts [Learn more about the Ticker Page →](/terminal/ticker-page/) ### Screeners [Section titled “Screeners”](#screeners) ![FinBrain Terminal Screeners](/_astro/terminal-screeners.CZ35KNjW.png) Filter stocks across all available tickers with 16 specialized screeners: * Price Forecasts (daily and monthly), Sentiment, Analyst Ratings * Insider Transactions, House Trades, Senate Trades, Congressional Trading (combined) * Put/Call Ratio, LinkedIn Metrics, App Ratings * Corporate Lobbying, Government Contracts, Reddit Mentions * News Tracker for market-moving headlines [Learn more about Screeners →](/terminal/screeners/) ### Portfolio [Section titled “Portfolio”](#portfolio) Track and analyze your investments: * **Multiple portfolios** for different strategies * **Transaction tracking** with execution prices and dates * **Real-time PnL** monitoring during market hours * **Performance analytics** including returns, volatility, and benchmark comparison [Learn more about Portfolio →](/terminal/portfolio/) ## Available Data [Section titled “Available Data”](#available-data) ### Price Forecasts [Section titled “Price Forecasts”](#price-forecasts) * Daily forecasts (10-day ahead) * Monthly forecasts (12-month ahead) * Confidence intervals displayed as bands * Directional signals (expected short/mid/long-term returns) ### Trading Activity [Section titled “Trading Activity”](#trading-activity) * Real-time SEC Form 4 insider filings * US House and Senate member trades * Filter by transaction type, member, party, or amount ### Sentiment & News [Section titled “Sentiment & News”](#sentiment--news) * AI-generated news sentiment scores * Sentiment trend charts with historical data * News feed with source attribution ### Alternative Data [Section titled “Alternative Data”](#alternative-data) * Analyst ratings and price targets * Options put/call ratios with volume data * LinkedIn employee and follower metrics * Mobile app store ratings (iOS and Android) * Corporate lobbying filings and expenditures * Federal government contract awards * Reddit mention tracking across investing subreddits ### Macro & Geopolitical [Section titled “Macro & Geopolitical”](#macro--geopolitical) * Treasury yield curves (US and EUR) * Central bank policy rates * CFTC futures positioning (COT reports) * Geopolitical event monitoring * Prediction market probabilities * US fiscal indicators (debt, deficit, interest) ## Getting Started [Section titled “Getting Started”](#getting-started) 1. **Sign up** at [finbrain.tech](https://www.finbrain.tech) if you haven’t already 2. **Log in** to access the Terminal at [terminal.finbrain.tech](https://terminal.finbrain.tech) 3. **Explore the Dashboard** for an overview of current market conditions 4. **Navigate to Markets** to browse asset-class-specific dashboards 5. **Enter a ticker** in the search box (or press Cmd+K) to view a Ticker Page 6. **Use Screeners** to find opportunities across alternative datasets 7. **Create a portfolio** to track your holdings ## Related Resources [Section titled “Related Resources”](#related-resources) * [Dashboard](/terminal/dashboard/) — Real-time market command center * [Intelligence](/terminal/intelligence/) — Geopolitical monitoring and COT data * [Markets Hub](/terminal/markets/overview/) — Asset class dashboards * [Ticker Page](/terminal/ticker-page/) — Individual stock analysis * [Screeners](/terminal/screeners/) — Filter stocks by alternative data * [Portfolio](/terminal/portfolio/) — Track and analyze holdings * [Python SDK](/integrations/python/) — Programmatic access to the same data * [API Reference](/api-reference/overview/) — Full API documentation # Portfolio > Create and manage multiple portfolios with transaction tracking, real-time PnL monitoring, and performance analytics in the FinBrain Terminal. The Portfolio section lets you create and manage multiple portfolios, track transactions with execution prices, and monitor performance with real-time analytics. ![Portfolio](/_astro/portfolio.DGNU29xg.png) ## Portfolio Management [Section titled “Portfolio Management”](#portfolio-management) ### Creating Portfolios [Section titled “Creating Portfolios”](#creating-portfolios) Create as many portfolios as you need: 1. Go to the **Portfolio** tab in the Terminal 2. Click **“Create Portfolio”** in the top right corner 3. Enter a portfolio name 4. Optionally set a starting cash balance 5. Choose a benchmark (S\&P 500, NASDAQ, etc.) ### Portfolio Types [Section titled “Portfolio Types”](#portfolio-types) Organize your investments with different portfolio types: * **Live Trading** - Track actual positions with real execution prices * **Paper Trading** - Test strategies without real money * **Watchlist** - Monitor stocks without position tracking ### Portfolio Settings [Section titled “Portfolio Settings”](#portfolio-settings) Configure each portfolio individually: | Setting | Description | | ---------------- | -------------------------------- | | Name | Portfolio display name | | Currency | USD, EUR, GBP, etc. | | Benchmark | Index for performance comparison | | Starting Capital | Initial investment amount | | Visibility | Private or shared with team | ## Transaction Tracking [Section titled “Transaction Tracking”](#transaction-tracking) ### Adding Transactions [Section titled “Adding Transactions”](#adding-transactions) Record every trade with full details: 1. Click **“Add Transaction”** 2. Select transaction type (Buy, Sell, Dividend, etc.) 3. Enter ticker symbol 4. Input execution details: * **Quantity** - Number of shares traded * **Price** - Execution price per share * **Date** - Transaction date * **Fees** - Commission and fees (optional) * **Notes** - Trade rationale (optional) ![Add Portfolio Transaction](/_astro/add-portfolio-transaction.Cijrz3H5.png) ### Transaction Types [Section titled “Transaction Types”](#transaction-types) Track all portfolio activities: | Type | Description | | -------- | ------------------------------ | | Buy | Open or add to a position | | Sell | Close or reduce a position | | Dividend | Cash dividend received | | Split | Stock split adjustment | | Transfer | Move shares between portfolios | ### Transaction History [Section titled “Transaction History”](#transaction-history) View all transactions in a searchable table: * Filter by ticker, date range, or transaction type * Sort by any column * Edit or delete past transactions ## Real-Time PnL Tracking [Section titled “Real-Time PnL Tracking”](#real-time-pnl-tracking) ### Position Summary [Section titled “Position Summary”](#position-summary) View current positions with live updates: | Column | Description | | ------------- | ---------------------- | | Ticker | Stock symbol | | Shares | Current share count | | Avg Cost | Average purchase price | | Current Price | Real-time market price | | Market Value | Current position value | | Day Change | Today’s gain/loss | | Total P\&L | Overall profit/loss | | Return % | Percentage return | ### P\&L Breakdown [Section titled “P\&L Breakdown”](#pl-breakdown) Understand your gains and losses: * **Realized P\&L** - Profits/losses from closed positions * **Unrealized P\&L** - Paper gains/losses on open positions * **Total P\&L** - Combined realized and unrealized * **Cost basis** - Total amount invested ### Live Updates [Section titled “Live Updates”](#live-updates) Portfolio values update in real-time during market hours: * Price updates every few seconds * P\&L recalculates automatically * Day change reflects intraday movements * Visual indicators for gains (green) and losses (red) ## Performance Analytics [Section titled “Performance Analytics”](#performance-analytics) ### Overview Dashboard [Section titled “Overview Dashboard”](#overview-dashboard) Get a quick snapshot of portfolio health: * **Total Value** - Current portfolio worth * **Day Change** - Today’s performance * **Total Return** - All-time return percentage * **vs Benchmark** - Performance relative to index ### Performance Charts [Section titled “Performance Charts”](#performance-charts) Visualize portfolio performance over time: #### Equity Curve [Section titled “Equity Curve”](#equity-curve) * Track portfolio value day by day * Compare against benchmark * Identify drawdown periods * Toggle between linear and log scale #### Return Distribution [Section titled “Return Distribution”](#return-distribution) * Histogram of daily returns * Compare to benchmark distribution * Identify volatility patterns #### Sector Allocation [Section titled “Sector Allocation”](#sector-allocation) * Pie chart of holdings by sector * Identify concentration risks * Track allocation changes over time ### Key Metrics [Section titled “Key Metrics”](#key-metrics) Advanced analytics for serious investors: | Metric | Description | | ------------ | ------------------------------- | | Total Return | Overall percentage gain/loss | | CAGR | Compound annual growth rate | | Volatility | Standard deviation of returns | | Sharpe Ratio | Risk-adjusted return measure | | Max Drawdown | Largest peak-to-trough decline | | Beta | Correlation with benchmark | | Alpha | Excess return vs benchmark | | Win Rate | Percentage of profitable trades | ### Time Period Analysis [Section titled “Time Period Analysis”](#time-period-analysis) Analyze performance across different periods: * **Today** - Intraday performance * **Week** - Trailing 7 days * **Month** - Trailing 30 days * **YTD** - Year to date * **1 Year** - Trailing 12 months * **All Time** - Since inception * **Custom** - Select specific date range ## Portfolio Actions [Section titled “Portfolio Actions”](#portfolio-actions) Manage your portfolios: * **Create** - Set up a new portfolio * **Edit** - Rename a portfolio or update its description * **Delete** - Permanently remove a portfolio and its transactions * **Add transactions** - Record buys, sells, dividends, splits and transfers * **Edit or delete transactions** - Correct an entry after the fact ## Tips for Effective Tracking [Section titled “Tips for Effective Tracking”](#tips-for-effective-tracking) 1. **Record trades promptly** - Add transactions right after execution for accurate tracking 2. **Include fees** - Commission adds up; track it for true performance 3. **Add notes** - Document your thesis for each trade 4. **Use benchmarks** - Compare against relevant indices 5. **Review regularly** - Check performance analytics weekly or monthly ## Related Resources [Section titled “Related Resources”](#related-resources) * [Ticker Page](/terminal/ticker-page/) - Research stocks before adding to portfolio * [Screeners](/terminal/screeners/) - Find new investment ideas * [Terminal Overview](/terminal/overview/) - Full terminal feature guide # Screeners > Filter and discover stocks using 16 alternative data screeners. Screen across all available tickers by price forecasts, insider buying, congressional trades, lobbying, government contracts, Reddit mentions, sentiment, and more. The Screeners section lets you filter stocks across all available tickers using alternative data criteria. With 16 screeners covering forecasts, government and regulatory filings, sentiment and social data, you can quickly identify opportunities based on the signals that matter to your strategy. ![Data Screeners](/_astro/terminal-screeners.CZ35KNjW.png) ## Available Screeners [Section titled “Available Screeners”](#available-screeners) ### Price Forecasts Screener [Section titled “Price Forecasts Screener”](#price-forecasts-screener) Filter stocks by quantitative price forecasts: * **Expected return** - Filter by short, mid, or long-term expected moves * **Direction** - Bullish or bearish predictions * **Market** - Limit to specific markets (S\&P 500, NASDAQ, etc.) ### Monthly Forecasts Screener [Section titled “Monthly Forecasts Screener”](#monthly-forecasts-screener) Screen longer-horizon price forecasts: * **Expected return** - Filter by 3-month, 6-month, or 12-month expected moves * **Direction** - Bullish or bearish forecasts * **Market** - Limit to specific markets ### Sentiment Screener [Section titled “Sentiment Screener”](#sentiment-screener) Find stocks with significant sentiment shifts: * **Current sentiment** - Filter by positive, negative, or neutral * **Date range** - Analyze specific time periods ### Insider Transactions Screener [Section titled “Insider Transactions Screener”](#insider-transactions-screener) Track executive buying and selling patterns: * **Transaction type** - Purchases, sales, or option exercises * **Insider role** - CEO, CFO, Directors, etc. * **Transaction size** - Filter by share count or dollar value Every row is dual-dated and carries its own provenance: * **Filed** - The date the Form 4 was filed and became public, alongside the transaction date. This is the look-ahead-free anchor * **Lag (D)** - Days from transaction to filing, computed from the two delivered dates. The SEC’s window is 2 business days * **Filing** - A direct link to the source Form 4 on SEC EDGAR, so any row can be audited against the official filing in one click ### House Trades Screener [Section titled “House Trades Screener”](#house-trades-screener) Monitor US House Representatives trading: * **Transaction type** - Purchases or sales * **Amount range** - Filter by the disclosed STOCK Act bracket * **Representative** - Search by specific member * **Disclosed** - The public filing date, shown next to the transaction date * **Lag (D)** - Days from trade to public disclosure. The STOCK Act allows up to 45 days, and the gap is a modellable feature in its own right * **Owner** - Whether the trade sits in the member’s own account, a spouse’s, a dependent child’s, or a joint account. Per-account disclosures are separate rows ### Senate Trades Screener [Section titled “Senate Trades Screener”](#senate-trades-screener) Track US Senator trading activity: * **Transaction type** - Purchases or sales * **Amount range** - Filter by the disclosed STOCK Act bracket * **Senator** - Search by specific member * **Disclosed** - The public filing date, shown next to the transaction date * **Lag (D)** - Days from trade to public disclosure * **Owner** - Member, spouse, dependent child, or joint account ### Analyst Ratings Screener [Section titled “Analyst Ratings Screener”](#analyst-ratings-screener) Screen stocks by Wall Street coverage: * **Rating type** - Upgrades, downgrades, initiations * **Signal** - Buy, Hold, Sell ratings * **Price target** - Above or below current price * **Institution** - Filter by specific firms ### Put/Call Screener [Section titled “Put/Call Screener”](#putcall-screener) Filter by options market sentiment: * **Put/call ratio** - High (bearish) or low (bullish) * **Volume** - Filter by options activity level ### LinkedIn Metrics Screener [Section titled “LinkedIn Metrics Screener”](#linkedin-metrics-screener) Screen by company growth signals: * **Employee count** - Filter by headcount * **Follower count** - Filter by LinkedIn followers * **Job openings** - Filter by open roles listed ### App Ratings Screener [Section titled “App Ratings Screener”](#app-ratings-screener) Filter consumer-facing companies by mobile app performance: * **App Store rating** - iOS app quality score * **Play Store rating** - Android app quality score * **Review volume** - Filter by number of reviews * **Install count** - Android installation numbers ### Corporate Lobbying Screener [Section titled “Corporate Lobbying Screener”](#corporate-lobbying-screener) Screen companies by lobbying activity and expenditures: * **Lobbying spend** - Filter by quarterly or annual lobbying expenditure * **Registrant firm** - Search by lobbying firm name * **Filing quarter** - Filter by reporting period ### Government Contracts Screener [Section titled “Government Contracts Screener”](#government-contracts-screener) Identify companies winning federal contracts: * **Contract value** - Filter by award amount * **Awarding agency** - Department of Defense, HHS, NASA, etc. * **Date range** - Filter by award date * **Industry** - Filter by NAICS industry description ### Patent Filings Screener [Section titled “Patent Filings Screener”](#patent-filings-screener) Track USPTO grants mapped to corporate assignees: * **Company** - Search by assignee * **Patent title** - Keyword search across grant titles * **Type** - Utility, design, or plant patents * **CPC class** - Filter by technology classification * **Claims** - Filter by claim count * **Grant date** - Filter by when the patent issued ### Reddit Mentions Screener [Section titled “Reddit Mentions Screener”](#reddit-mentions-screener) Track retail attention across investing subreddits: * **Mention count** - Filter by total mentions * **Subreddit** - Focus on specific communities (wallstreetbets, stocks, etc.) * **Timeframe** - Filter by data collection period ### Congressional Trading Screener [Section titled “Congressional Trading Screener”](#congressional-trading-screener) A combined view of House and Senate member trades with additional filtering: * **Chamber filter** - House only, Senate only, or combined * **Transaction type** - Purchases or sales * **Amount range** - Filter by the disclosed STOCK Act bracket * **Member** - Search by specific politician * **Disclosed** - The public filing date, shown next to the transaction date This screener combines the data from the House and Senate screeners above into a single view with a chamber toggle for convenience. ### News Tracker [Section titled “News Tracker”](#news-tracker) Stay on top of market-moving news: * **Keyword search** - Find news by topic or company * **Sentiment filter** - Positive, negative, or neutral news * **Source** - Filter by publication * **Date range** - Today, this week, custom range ## Using the Screeners [Section titled “Using the Screeners”](#using-the-screeners) ![Insider Trading Screener](/_astro/insider-trading-screener.CdiKudkh.png) ### Basic Workflow [Section titled “Basic Workflow”](#basic-workflow) 1. **Select a screener** from the left sidebar 2. **Set your filters** using the controls at the top 3. **Review results** in the main table 4. **Sort and rank** by clicking column headers 5. **Click any ticker** to view its full Ticker Page ### Combining Filters [Section titled “Combining Filters”](#combining-filters) Each screener supports multiple filters that work together: * Filters are applied with AND logic * Results update in real-time as you adjust * Clear individual filters or reset all at once ## Screener Results [Section titled “Screener Results”](#screener-results) Results display in a sortable table showing: | Column | Description | | ----------------- | ---------------------------------------- | | Ticker | Stock symbol (click to view Ticker Page) | | Company | Company name | | Primary Metric | Main data point for the screener type | | Secondary Metrics | Additional relevant data | | Date | When the data was recorded | ## Exporting Results [Section titled “Exporting Results”](#exporting-results) Every screener has an **Export CSV** button in its summary bar. It downloads the rows currently matching your filters, in the sort order on screen, across all pages — not just the page you are looking at. The row count on the button is what the file will contain. Notes on the file: * Dates are written as ISO calendar dates (`2026-03-15`) rather than the display format, so the file parses cleanly in pandas, Excel, or R * It is UTF-8 with a byte-order mark, so Excel opens non-ASCII company and politician names correctly * The export contains the rows loaded in that view. Full historical depth is served through the [API](/api-reference/overview/), the [Python SDK](/integrations/python/), and MCP ## Pro Tips [Section titled “Pro Tips”](#pro-tips) 1. **Start broad, then narrow** - Begin with loose filters and tighten to find the best matches 2. **Combine with fundamentals** - Use alternative data alongside traditional metrics 3. **Check regularly** - Monitor screeners for new signals as data updates 4. **Cross-reference** - Check signals across multiple screeners for confirmation ## Related Resources [Section titled “Related Resources”](#related-resources) * [Ticker Page](/terminal/ticker-page/) - Deep dive into individual stocks * [Portfolio](/terminal/portfolio/) - Track your screener picks * [Datasets](/datasets/ai-forecasts/) - Learn about the underlying data # Ticker Page > Explore individual stocks with interactive price charts and alternative data visualizations. View news, analyst ratings, insider transactions, congressional trades, lobbying, government contracts, and Reddit mentions in one place. The Ticker Page provides a comprehensive view of any stock, combining interactive price charts with all available alternative datasets. Enter any ticker to get a complete picture of the company’s data. ![FinBrain Terminal Ticker Page](/_astro/terminal-ticker.x_84Nb4g.png) ## Interactive Price Chart [Section titled “Interactive Price Chart”](#interactive-price-chart) The main chart displays historical price data with full interactivity: * **Price history** with adjustable time ranges * **Volume data** in a secondary panel * **Technical indicators** and drawing tools * **Multiple chart types** including candlestick and line views ![Interactive Price Chart](/_astro/interactive-chart.BIpdD0FH.png) ### Chart Controls [Section titled “Chart Controls”](#chart-controls) * Zoom in/out with mouse wheel or pinch gestures * Drag to pan across time periods * Click and drag to select a specific date range ## Price Forecast Charts [Section titled “Price Forecast Charts”](#price-forecast-charts) Dedicated charts display FinBrain’s price forecasts: ![Price Forecast Charts](/_astro/ai-forecast-charts.CqdL58C1.png) ### Daily Forecasts [Section titled “Daily Forecasts”](#daily-forecasts) View 10-day ahead price predictions: * **Predicted price path** for the next 10 trading days * **Confidence intervals** displayed as bands * **Expected short/mid/long-term returns** as percentage signals ### Monthly Forecasts [Section titled “Monthly Forecasts”](#monthly-forecasts) View 12-month ahead price predictions: * **Predicted price path** for the next 12 months * **Confidence intervals** displayed as bands * **Long-term directional signals** ## Alternative Data Charts [Section titled “Alternative Data Charts”](#alternative-data-charts) Below the price and forecast charts, you’ll find dedicated visualizations for each alternative dataset: ![Alternative Data Charts](/_astro/alternative-data-charts.CISWoXg2.png) ### Sentiment Chart [Section titled “Sentiment Chart”](#sentiment-chart) Track news sentiment over time with an interactive line chart showing: * Daily sentiment scores (-1 to 1 scale) * Trend indicators * Correlation with price movements ### LinkedIn Metrics [Section titled “LinkedIn Metrics”](#linkedin-metrics) Visualize company growth signals: * Employee count over time * Follower count trends * Growth rate indicators ### App Ratings [Section titled “App Ratings”](#app-ratings) For consumer-facing companies, view mobile app performance: * App Store rating history * Play Store rating history * Review count trends * Install count (Android) * An app selector when the company publishes more than one app, so you can switch between product lines instead of reading a single blended number. Apps are listed biggest first, with each one’s ratings count beside its name ### Put/Call Ratio [Section titled “Put/Call Ratio”](#putcall-ratio) Monitor options market sentiment: * Historical put/call ratio * Volume trends * Unusual activity markers ### Reddit Mentions [Section titled “Reddit Mentions”](#reddit-mentions) Track social sentiment and attention for the ticker across investing subreddits: * Mention count over time as a bar chart * Breakdown by subreddit (wallstreetbets, stocks, investing, options, and more) * Useful for identifying retail attention spikes before price moves For the full dataset, see the [Reddit Mentions Dataset](/datasets/reddit-mentions/). ## Data Tables [Section titled “Data Tables”](#data-tables) The Ticker Page also displays detailed tables for datasets that are better viewed as individual records: ![Data Tables](/_astro/congressional-trading-table.D489Jknn.png) ### News Feed [Section titled “News Feed”](#news-feed) Recent news articles with: * Publication date and source * Headline and summary * Sentiment score for each article ### Analyst Ratings [Section titled “Analyst Ratings”](#analyst-ratings) Wall Street coverage in table format: | Column | Description | | ------------ | ------------------------------ | | Date | Rating announcement date | | Institution | Brokerage or research firm | | Signal | Buy, Hold, Sell, etc. | | Target Price | Analyst’s price target | | Type | Upgrade, Downgrade, Initiation | ### Insider Transactions [Section titled “Insider Transactions”](#insider-transactions) SEC Form 4 filings displayed as: | Column | Description | | ----------- | ---------------------------------------------------------------------- | | Date | Transaction date | | Filed | Date the Form 4 was filed and became public — the point-in-time anchor | | Insider | Name and title | | Transaction | Buy, Sale, Option Exercise | | Shares | Number of shares | | Price | Transaction price | | Value | Total USD value | | Filing | Link to the source Form 4 on SEC EDGAR | ### Congressional Trades [Section titled “Congressional Trades”](#congressional-trades) House and Senate member transactions: | Column | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | Date | Transaction date, as disclosed | | Disclosed | Public filing date — the look-ahead-free anchor | | Lag | Days from transaction to public disclosure. The STOCK Act allows up to 45 days | | Member | Representative or Senator name | | Owner | Account the trade sits in: member, spouse, dependent child, or joint | | Chamber | House or Senate | | Type | Purchase or Sale | | Amount | Disclosed STOCK Act bracket. A flag marks the small share of rows delivered as filed rather than normalized, with the original string on hover | ### Corporate Lobbying [Section titled “Corporate Lobbying”](#corporate-lobbying) Lobbying disclosure filings for the company: | Column | Description | | ------------------- | --------------------------------------------- | | Date | Filing date | | Registrant | Lobbying firm name | | Quarter | Filing quarter (Q1-Q4) | | Income/Expenses | Reported lobbying expenditure | | Issue Codes | Policy areas lobbied on (e.g., TAX, TRD, COM) | | Government Entities | Bodies lobbied (e.g., Senate, House) | For the full dataset, see the [Corporate Lobbying Dataset](/datasets/corporate-lobbying/). ### Government Contracts [Section titled “Government Contracts”](#government-contracts) Federal contract awards associated with the company from USAspending.gov: | Column | Description | | --------------- | ----------------------------------- | | Award Date | Contract start date | | Awarding Agency | Federal agency issuing the contract | | Description | Contract description | | Award Amount | Dollar value of the contract | | End Date | Contract end date | For the full dataset, see the [Government Contracts Dataset](/datasets/government-contracts/). ## Navigation [Section titled “Navigation”](#navigation) Use the tabs at the top of the Ticker Page to quickly jump between: 1. **Overview** - Summary of all key metrics 2. **Predictions** - Detailed price forecast data 3. **Sentiment** - News and sentiment analysis 4. **Alternative Data** - All other datasets 5. **Fundamentals** - Basic company information ## Related Resources [Section titled “Related Resources”](#related-resources) * [Screeners](/terminal/screeners/) - Filter stocks by alternative data criteria * [Portfolio](/terminal/portfolio/) - Track and analyze your holdings * [Price Forecasts Dataset](/datasets/ai-forecasts/) - Learn more about forecast data # Terms & Conditions ## Introduction [Section titled “Introduction”](#introduction) Welcome to FinBrain Technologies (“FinBrain,” “we,” “us,” or “our”). These Terms and Conditions (“Terms”) govern your access to and use of the FinBrain website (finbrain.tech), FinBrain Terminal (terminal.finbrain.tech), FinBrain REST API, Python SDK, Model Context Protocol (MCP) integration, and all related services, interfaces, content, and data (collectively, the “Services”). By accessing, registering for, or using any of the Services, you agree to be bound by these Terms. If you do not agree to these Terms, you must not access or use the Services. ## Description of Services [Section titled “Description of Services”](#description-of-services) FinBrain provides aggregated alternative data and analytics for publicly traded companies and global markets. Our data is derived from publicly available sources, proprietary models, and licensed feeds. The categories we cover include, without limitation: * Quantitative price forecasts and trading signals * Public disclosure and filing data * Public insider and legislative trading activity * Public corporate influence and regulatory filings * Public government spending and contract awards * Public sentiment, news, and social activity indicators * Public employment, product, and consumer interest indicators * Public macroeconomic, market structure, and positioning indicators * Public event and risk monitoring indicators We do not disclose the specific sources, providers, or collection methodologies underlying our datasets except as required to operate the Services. The composition, coverage, and sources of any dataset may change at any time without notice. ## Account Registration [Section titled “Account Registration”](#account-registration) To access paid Services you must: * Register an account with accurate, current, and complete information * Maintain the confidentiality of your credentials, API keys, and access tokens * Promptly notify us of any unauthorized use of your account * Be at least 18 years of age or the age of legal majority in your jurisdiction * Not be on any U.S. or international sanctions list or otherwise prohibited from receiving services You are solely responsible for all activity that occurs under your account and for all use of any API keys issued to you. ## Subscription and Payments [Section titled “Subscription and Payments”](#subscription-and-payments) ### Plans and Pricing [Section titled “Plans and Pricing”](#plans-and-pricing) | Plan | Monthly | Annual | | -------------------------------- | ------- | ------ | | Professional (FinBrain Terminal) | $199 | $1,990 | | Enterprise | Custom | Custom | Current pricing is published at [finbrain.tech](https://finbrain.tech) and may be updated from time to time. Enterprise pricing is negotiated separately. ### Billing [Section titled “Billing”](#billing) * Subscriptions renew automatically on a monthly or annual basis until cancelled * All fees are stated in U.S. dollars and are exclusive of taxes, which are your responsibility * All fees are non-refundable except where required by law * We may change pricing for future billing cycles with reasonable notice (typically 30 days) * Failed payments may result in suspension or termination of access ### Cancellation [Section titled “Cancellation”](#cancellation) You may cancel your subscription at any time from your account dashboard. Cancellation takes effect at the end of your current billing period; no prorated refunds are provided. ## License Grant [Section titled “License Grant”](#license-grant) Subject to these Terms and your timely payment of applicable fees, FinBrain grants you a limited, non-exclusive, non-transferable, non-sublicensable, revocable license to access and use the Services and the data delivered through them solely for your internal business or personal research purposes. All rights not expressly granted are reserved by FinBrain. ## Acceptable Use [Section titled “Acceptable Use”](#acceptable-use) You agree that you will NOT, and will not permit any third party to: * Use the Services for any illegal, fraudulent, or unauthorized purpose, or in violation of any applicable law, regulation, or exchange rule * **Redistribute, resell, republish, sublicense, syndicate, or otherwise make available the data to any third party** without purchasing a separate redistribution license from FinBrain * Use the data to build, train, or improve any product or service that competes with FinBrain * Use the data as a direct input to train or fine-tune machine learning models, large language models, or other AI systems, except as expressly permitted in your subscription tier or under a separate written agreement * Incorporate the data into any data product, feed, index, benchmark, or derivative work offered to third parties * Reverse engineer, decompile, disassemble, or otherwise attempt to derive the source code, algorithms, or methodologies underlying the Services * Circumvent, disable, or interfere with any authentication, rate limit, access control, or security feature of the Services * Share, lease, transfer, or otherwise expose your API key or account credentials * Use automated tools (including scrapers, crawlers, or bots) to access the Services in a manner that exceeds your subscription’s rate or volume limits * Use the Services to engage in market manipulation, insider trading, spoofing, or any other unlawful market activity * Remove, obscure, or alter any proprietary notices or markings Violation of the Acceptable Use provisions may result in immediate suspension or termination without refund, and may also give rise to legal claims for damages. ## AI Forecasts and Predictions [Section titled “AI Forecasts and Predictions”](#ai-forecasts-and-predictions) A portion of the Services consists of AI-generated forecasts, predictions, probabilities, sentiment scores, and related analytical outputs (“AI Outputs”). You acknowledge and agree that: * AI Outputs are **probabilistic estimates**, not guarantees, and are inherently uncertain * AI Outputs may be inaccurate, incomplete, or materially wrong at any time * Past performance of any AI Output, model, or signal is not indicative of future results * AI Outputs may reflect biases in source data, model assumptions, or training procedures * You are solely responsible for evaluating the suitability of any AI Output for your use case * FinBrain accepts no liability whatsoever for trading losses, investment decisions, or other outcomes based on AI Outputs ## MCP and Third-Party AI Integrations [Section titled “MCP and Third-Party AI Integrations”](#mcp-and-third-party-ai-integrations) The Services include the FinBrain MCP server and may be accessed by third-party large language models (“LLMs”) and AI assistants (including but not limited to Claude, ChatGPT, and custom agents) (“Third-Party AI”). You acknowledge and agree that: * FinBrain does not control Third-Party AI and is not responsible for their outputs, behavior, errors, or omissions * Third-Party AI may misinterpret, misrepresent, hallucinate, or fabricate information when processing FinBrain data * You are solely responsible for validating any output produced by Third-Party AI before relying on it * FinBrain accepts no liability whatsoever for losses, damages, or decisions arising from outputs generated by Third-Party AI, regardless of whether the underlying FinBrain data is correct * You remain bound by the redistribution and acceptable use provisions of these Terms when integrating FinBrain data into any Third-Party AI workflow ## Data Accuracy and Availability [Section titled “Data Accuracy and Availability”](#data-accuracy-and-availability) ### Not Financial Advice [Section titled “Not Financial Advice”](#not-financial-advice) **The Services and all data, forecasts, signals, and analytics provided through them are for informational purposes only and do not constitute financial, investment, legal, tax, accounting, or other professional advice.** FinBrain is not a registered investment advisor, broker-dealer, or fiduciary. You should consult qualified professionals before making any investment, trading, or business decision. ### No Guarantee of Accuracy, Completeness, or Timeliness [Section titled “No Guarantee of Accuracy, Completeness, or Timeliness”](#no-guarantee-of-accuracy-completeness-or-timeliness) FinBrain makes no representation or warranty that the data is accurate, complete, current, uninterrupted, or free of errors or omissions. Data is aggregated from multiple sources and may contain: * Errors, inaccuracies, or inconsistencies in source data * Missing, delayed, stale, or revised data points * Gaps in coverage across tickers, markets, dates, or fields * Changes, corrections, or removals at any time without notice **FinBrain accepts no liability for any error, omission, delay, interruption, corruption, or unavailability of data**, whether caused by source data issues, technical failures, upstream provider changes, or any other cause. You use the data at your own risk and are solely responsible for verifying any data before relying on it. ### No Warranty [Section titled “No Warranty”](#no-warranty) THE SERVICES AND ALL DATA, CONTENT, AND MATERIALS ARE PROVIDED “AS IS” AND “AS AVAILABLE,” WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT. FINBRAIN DOES NOT WARRANT THAT THE SERVICES WILL MEET YOUR REQUIREMENTS, BE UNINTERRUPTED, SECURE, OR ERROR-FREE, OR THAT ANY DEFECTS WILL BE CORRECTED. ## Intellectual Property [Section titled “Intellectual Property”](#intellectual-property) All content, data, software, models, algorithms, interfaces, designs, trademarks, logos, and other materials made available through the Services are owned by FinBrain Technologies or its licensors and are protected by intellectual property laws. Nothing in these Terms transfers any ownership interest in the Services to you. Your subscription grants only the limited license described above. ## Redistribution and Licensing [Section titled “Redistribution and Licensing”](#redistribution-and-licensing) The data delivered through the Services is licensed for your internal use only. **Redistribution, resale, syndication, or external client-facing display of the data — in raw, transformed, derivative, or aggregated form — is prohibited unless you have purchased a separate redistribution license from FinBrain.** Enterprise and redistribution licenses are available on a negotiated basis. Contact to discuss licensing terms for your use case. ## Limitation of Liability [Section titled “Limitation of Liability”](#limitation-of-liability) TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW: * FINBRAIN, ITS OFFICERS, DIRECTORS, EMPLOYEES, CONTRACTORS, AFFILIATES, AND LICENSORS SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, INCLUDING BUT NOT LIMITED TO LOSS OF PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS OPPORTUNITIES, ARISING OUT OF OR RELATING TO THE SERVICES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES * FINBRAIN SHALL NOT BE LIABLE FOR ANY TRADING LOSS, INVESTMENT LOSS, OR OTHER FINANCIAL HARM RESULTING FROM YOUR USE OF, OR RELIANCE ON, ANY DATA, FORECAST, SIGNAL, OR OUTPUT PROVIDED BY THE SERVICES * FINBRAIN SHALL NOT BE LIABLE FOR ANY OUTPUT, HALLUCINATION, OR ACTION OF ANY THIRD-PARTY AI OR LLM INTERACTING WITH THE SERVICES * FINBRAIN’S TOTAL AGGREGATE LIABILITY FOR ANY CLAIM ARISING OUT OF OR RELATING TO THESE TERMS OR THE SERVICES SHALL NOT EXCEED THE GREATER OF (A) THE AMOUNT YOU PAID TO FINBRAIN IN THE THREE (3) MONTHS PRECEDING THE EVENT GIVING RISE TO THE CLAIM OR (B) ONE HUNDRED U.S. DOLLARS ($100) These limitations apply to the fullest extent permitted by law even if any remedy fails of its essential purpose. ## Indemnification [Section titled “Indemnification”](#indemnification) You agree to indemnify, defend, and hold harmless FinBrain Technologies and its officers, directors, employees, contractors, affiliates, and licensors from and against any and all claims, demands, losses, liabilities, damages, costs, and expenses (including reasonable attorneys’ fees) arising out of or relating to: * Your access to or use of the Services * Your violation of these Terms * Your violation of any third-party right, including any intellectual property or privacy right * Your trading, investment, or business decisions * Any content or data you submit or transmit through the Services ## Third-Party Services [Section titled “Third-Party Services”](#third-party-services) The Services rely on third-party infrastructure and service providers, including cloud hosting, payment processing, and analytics. Your use of the Services is also subject to the applicable terms and privacy policies of those providers. FinBrain is not responsible for the acts, omissions, or policies of third-party providers. ## Service Availability and Modifications [Section titled “Service Availability and Modifications”](#service-availability-and-modifications) We strive for high availability but do not guarantee uninterrupted or error-free access to the Services. We may: * Perform scheduled or emergency maintenance * Suspend access for security, legal, or technical reasons * Add, modify, deprecate, or discontinue features, datasets, or endpoints at any time, with or without notice * Enforce rate limits and usage quotas FinBrain is not liable for any loss or damage arising from any such change, suspension, or discontinuation. ## Suspension and Termination [Section titled “Suspension and Termination”](#suspension-and-termination) We may suspend or terminate your access to the Services, with or without notice, if: * You breach these Terms * You fail to pay applicable fees * We reasonably suspect fraudulent, abusive, or unlawful activity * We are required to do so by law or legal process * We decide to discontinue the Services or a material portion of them Upon termination, your license to use the Services ends immediately. Provisions of these Terms that by their nature are intended to survive termination (including, without limitation, Intellectual Property, Limitation of Liability, Indemnification, and Governing Law) shall survive. ## Modifications to these Terms [Section titled “Modifications to these Terms”](#modifications-to-these-terms) We may update these Terms from time to time. Material changes will be communicated by updating the “Last updated” date above and, where appropriate, notifying you by email or through the Services. Your continued use of the Services after changes take effect constitutes acceptance of the updated Terms. ## Governing Law and Jurisdiction [Section titled “Governing Law and Jurisdiction”](#governing-law-and-jurisdiction) These Terms are governed by the laws of the State of Delaware, United States, without regard to its conflict of law principles. Subject to the Dispute Resolution section below, the state and federal courts located in Delaware shall have exclusive jurisdiction over any non-arbitrable disputes. ## Dispute Resolution [Section titled “Dispute Resolution”](#dispute-resolution) Any dispute, claim, or controversy arising out of or relating to these Terms or the Services shall be resolved through binding, confidential arbitration administered by the American Arbitration Association under its Commercial Arbitration Rules. The arbitration shall be conducted in English. Notwithstanding the foregoing, either party may seek injunctive or equitable relief in court for actual or threatened infringement of intellectual property rights. **Class Action Waiver:** You and FinBrain agree that any dispute shall be brought in an individual capacity only and not as a plaintiff or class member in any purported class, collective, or representative proceeding. ## Severability [Section titled “Severability”](#severability) If any provision of these Terms is held to be invalid or unenforceable, the remaining provisions shall remain in full force and effect. ## Entire Agreement [Section titled “Entire Agreement”](#entire-agreement) These Terms, together with our [Privacy Policy](/privacy-policy/), constitute the entire agreement between you and FinBrain regarding the Services and supersede all prior agreements or understandings. ## Contact Information [Section titled “Contact Information”](#contact-information) For questions about these Terms: **Email:** **Website:** [finbrain.tech](https://finbrain.tech) *** *Last updated: April 18, 2026*