Sentiments API
Sentiments API
Section titled “Sentiments API”Retrieve AI-powered sentiment analysis scores derived from financial news. Get sentiment scores for any ticker.
Endpoint
Section titled “Endpoint”GET /v1/sentiments/{market}/{ticker}Authentication
Section titled “Authentication”Requires API key via token query parameter.
Parameters
Section titled “Parameters”Path Parameters
Section titled “Path Parameters”| Parameter | Type | Required | Description |
|---|---|---|---|
market | string | Yes | Market identifier (e.g., S&P 500, NASDAQ) |
ticker | string | Yes | Stock ticker symbol (e.g., AAPL, MSFT) |
Query Parameters
Section titled “Query Parameters”| Parameter | Type | Required | Description |
|---|---|---|---|
token | string | Yes | Your API key |
dateFrom | string | No | Start date (YYYY-MM-DD) |
dateTo | string | No | End date (YYYY-MM-DD) |
Request
Section titled “Request”# Get sentiment datacurl "https://api.finbrain.tech/v1/sentiments/S%26P%20500/AAPL?token=YOUR_API_KEY"
# With date rangecurl "https://api.finbrain.tech/v1/sentiments/S%26P%20500/AAPL?token=YOUR_API_KEY&dateFrom=2024-01-01&dateTo=2024-01-31"from finbrain import FinBrainClient
fb = FinBrainClient(api_key="YOUR_API_KEY")
# Get sentiment as DataFrame (recommended)df = fb.sentiments.ticker("S&P 500", "AAPL", as_dataframe=True)print(df.tail())# sentiment# date# 2024-11-04 0.186# 2024-11-01 0.339
# Get raw JSON responsesentiment = fb.sentiments.ticker("S&P 500", "AAPL")print(sentiment)
# With date rangehistorical = fb.sentiments.ticker( "S&P 500", "AAPL", date_from="2024-01-01", date_to="2024-01-31", as_dataframe=True)#include <iostream>#include <string>#include <curl/curl.h>#include <nlohmann/json.hpp>
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& market, const std::string& ticker, 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/v1/sentiments/" + std::string(encoded_market) + "/" + ticker + "?token=" + api_key; curl_free(encoded_market);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_perform(curl); curl_easy_cleanup(curl); }
return json::parse(response);}
int main() { auto data = get_sentiment("S&P 500", "AAPL", "YOUR_API_KEY");
std::cout << "Ticker: " << data["ticker"].get<std::string>() << " (" << data["name"].get<std::string>() << ")" << std::endl;
for (auto& [date, score] : data["sentimentAnalysis"].items()) { std::cout << date << ": " << score.get<std::string>() << std::endl; }
return 0;}use reqwest::blocking::Client;use serde::Deserialize;use std::collections::HashMap;use std::error::Error;
#[derive(Debug, Deserialize)]struct SentimentResponse { ticker: String, name: String, #[serde(rename = "sentimentAnalysis")] sentiment_analysis: HashMap<String, String>,}
fn get_sentiment(market: &str, ticker: &str, api_key: &str) -> Result<SentimentResponse, Box<dyn Error>> { let url = format!( "https://api.finbrain.tech/v1/sentiments/{}/{}?token={}", urlencoding::encode(market), ticker, api_key );
let client = Client::new(); let response: SentimentResponse = client.get(&url).send()?.json()?;
Ok(response)}
fn main() -> Result<(), Box<dyn Error>> { let data = get_sentiment("S&P 500", "AAPL", "YOUR_API_KEY")?;
println!("Ticker: {} ({})", data.ticker, data.name); for (date, score) in &data.sentiment_analysis { let score_f: f64 = score.parse().unwrap_or(0.0); println!("{}: {:.3}", date, score_f); }
Ok(())}import requestsfrom urllib.parse import quote
market = "S&P 500"ticker = "AAPL"
response = requests.get( f"https://api.finbrain.tech/v1/sentiments/{quote(market)}/{ticker}", params={"token": "YOUR_API_KEY"})sentiment = response.json()const market = encodeURIComponent("S&P 500");const ticker = "AAPL";
const response = await fetch( `https://api.finbrain.tech/v1/sentiments/${market}/${ticker}?token=YOUR_API_KEY`);const sentiment = await response.json();Response
Section titled “Response”Success Response (200 OK)
Section titled “Success Response (200 OK)”{ "ticker": "AMZN", "name": "Amazon.com Inc.", "sentimentAnalysis": { "2021-12-15": "0.223", "2021-12-14": "0.037", "2021-12-13": "-0.038", "2021-12-10": "0.156", "2021-12-09": "0.089" }}Response Fields
Section titled “Response Fields”| Field | Type | Description |
|---|---|---|
ticker | string | Stock ticker symbol |
name | string | Company name |
sentimentAnalysis | object | Object with date keys and sentiment score values (as strings) |
sentimentAnalysis Object
Section titled “sentimentAnalysis Object”The sentimentAnalysis field is an object where each key is a date (YYYY-MM-DD) and the value is the sentiment score as a string.
| Value Range | Interpretation |
|---|---|
| ”-1” to “1” | Sentiment score from bearish to bullish (stored as string) |
Sentiment Score Interpretation
Section titled “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”Basic Sentiment Check
Section titled “Basic Sentiment Check”from finbrain import FinBrainClient
fb = FinBrainClient(api_key="YOUR_API_KEY")
sentiment = fb.sentiments.ticker("S&P 500", "AAPL")
# Get latest sentiment (most recent date)sentiment_data = sentiment["sentimentAnalysis"]dates = sorted(sentiment_data.keys(), reverse=True)latest_date = dates[0]score = float(sentiment_data[latest_date]) # Convert string to float
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”from finbrain import FinBrainClient
fb = FinBrainClient(api_key="YOUR_API_KEY")
def detect_sentiment_spike(market, ticker): """Detect unusual sentiment activity""" data = fb.sentiments.ticker(market, ticker) sentiment_data = data["sentimentAnalysis"] dates = sorted(sentiment_data.keys(), reverse=True)
if len(dates) < 10: return None
# Calculate baseline from historical data (convert strings to floats) historical_scores = [float(sentiment_data[d]) for d in dates[1:10]] avg_score = sum(historical_scores) / len(historical_scores)
# Compare to latest latest_score = float(sentiment_data[dates[0]]) 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("S&P 500", "TSLA")if alerts: print("Sentiment Alerts:") for alert in alerts: print(f" - {alert}")Sentiment Trend Analysis
Section titled “Sentiment Trend Analysis”from finbrain import FinBrainClient
fb = FinBrainClient(api_key="YOUR_API_KEY")
def analyze_sentiment_trend(market, ticker, days=14): """Analyze sentiment trend over time""" data = fb.sentiments.ticker(market, ticker) sentiment_data = data["sentimentAnalysis"] dates = sorted(sentiment_data.keys(), reverse=True)
if len(dates) < days: return None
recent_dates = dates[:days//2] older_dates = dates[days//2:days]
# Convert string scores to floats for calculation recent_avg = sum(float(sentiment_data[d]) for d in recent_dates) / len(recent_dates) older_avg = sum(float(sentiment_data[d]) for d in older_dates) / len(older_dates)
change = recent_avg - older_avg
if change > 0.1: trend = "improving" elif change < -0.1: trend = "deteriorating" else: trend = "stable"
return { "ticker": ticker, "recent_sentiment": recent_avg, "older_sentiment": older_avg, "change": change, "trend": trend }
result = analyze_sentiment_trend("S&P 500", "NVDA")print(f"Sentiment trend: {result['trend']} ({result['change']:+.3f})")Errors
Section titled “Errors”| Code | Error | Description |
|---|---|---|
| 400 | Bad Request | Invalid market or ticker |
| 401 | Unauthorized | Invalid or missing API key |
| 404 | Not Found | Ticker not found |
| 500 | Internal Server Error | Server-side error |
Related
Section titled “Related”- News Sentiment Dataset - Use cases and analysis examples
- Ticker Predictions - Get price predictions
- Analyst Ratings - Get analyst recommendations
- Put/Call Data - Get options sentiment