← Blog
6 min read

How to Add Sentiment Analysis to Your Trading Bot

Numeric sentiment scores per entity, sentiment history, shift detection, and composite trading signals. Turn headlines into quantitative signals your bot can trade on.

Most trading bots treat sentiment as a string — “bullish” or “bearish” — if they use it at all. That's not a signal you can threshold on. You need a number.

Polaris scores every entity from -1.0 (extremely bearish) to +1.0 (extremely bullish) on every brief. This tutorial shows how to use numeric sentiment, history, shift detection, and composite signals in your trading bot.

Get Current Sentiment

python
import httpx

API_KEY = "pr_live_xxx"
BASE = "https://api.thepolarisreport.com"
HEADERS = {"X-API-Key": API_KEY}

# Batch sentiment for multiple tickers
resp = httpx.get(f"{BASE}/api/v1/entities/sentiment",
    params={"tickers": "NVDA,AAPL,TSLA,AMD"},
    headers=HEADERS)

for entity in resp.json()["entities"]:
    print(f"{entity['ticker']}: {entity['sentiment_score']:+.2f} ({entity['trend']})")

Track Sentiment Over Time

python
# Daily sentiment history — use for trend analysis
resp = httpx.get(f"{BASE}/api/v1/ticker/NVDA/history",
    params={"days": 30},
    headers=HEADERS)

for day in resp.json()["history"]:
    if day["brief_count"] > 0:
        print(f"{day['date']}: avg={day['avg_sentiment']:+.2f} ({day['brief_count']} briefs)")

Detect Sentiment Shifts

The signals endpoint detects when sentiment moves beyond a threshold. Set your own sensitivity.

python
# Alert when sentiment shifts more than 0.3
resp = httpx.get(f"{BASE}/api/v1/ticker/NVDA/signals",
    params={"days": 30, "threshold": 0.3},
    headers=HEADERS)

for signal in resp.json()["signals"]:
    direction = "BEARISH" if signal["sentiment_shift"] < 0 else "BULLISH"
    print(f"{signal['date']}: {direction} shift ({signal['sentiment_shift']:+.2f})")
    print(f"  Trigger: {signal.get('trigger_headline','')}")

Composite Trading Signal

The composite score combines sentiment, momentum, volume, and events into a single number your bot can threshold on.

python
resp = httpx.get(f"{BASE}/api/v1/ticker/NVDA/score", headers=HEADERS)
score = resp.json()

print(f"Signal: {score['signal']} (score: {score['composite_score']:.3f})")
print(f"  Sentiment: {score['components']['sentiment']['current_24h']:+.2f}")
print(f"  Momentum: {score['components']['momentum']['direction']}")
print(f"  Volume: {score['components']['volume']['briefs_24h']} briefs/24h")

# Simple trading logic
if score["composite_score"] > 0.6:
    print("→ Strong bullish signal — consider entry")
elif score["composite_score"] < -0.3:
    print("→ Bearish signal — consider exit or short")

Sentiment-Aware Trading Loop

python
import time

WATCHLIST = ["NVDA", "AMD", "AAPL", "TSLA", "MSFT"]

while True:
    for ticker in WATCHLIST:
        score = httpx.get(f"{BASE}/api/v1/ticker/{ticker}/score",
            headers=HEADERS).json()

        if score["signal"] in ("buy", "strong_bullish"):
            print(f"BUY signal: {ticker} (score: {score['composite_score']:.3f})")
        elif score["signal"] in ("sell", "strong_bearish"):
            print(f"SELL signal: {ticker} (score: {score['composite_score']:.3f})")

    time.sleep(300)  # Check every 5 minutes

Get Started