News sentiment analysis in Python

World News API returns a sentiment score from -1 (negative) to 1 (positive) with every English and German article, so you do not need to run your own model. Filter with min-sentiment and max-sentiment, pull the articles for each company or person with entities=ORG:Tesla, and average the scores per day. Tracking 2 companies over 7 days with up to 200 articles each costs at most 8 points, well inside the free plan's 50 a day.

  • Field: sentiment, a number in [-1, 1], one score per article.
  • Languages: English and German only. Set language=en or language=de.
  • Filters: min-sentiment and max-sentiment, both in [-1, 1].
  • Entities: ORG:, PER: and LOC:, for example ORG:Tesla (semantic types).
  • Cost: 1 point per request plus 0.01 per article; 100 articles cost 2 points.
  • History: the last month on the free plan, back to January 1, 2022 on Reporter and higher.

What you'll build

A script that, for each entity you list, fetches the last 7 days of English articles, then prints the number of articles, the mean sentiment and the share of negative articles per day. A pandas version turns the same data into a table with one column per entity and a rolling average.

Prerequisites

pip install requests pandas
export WORLD_NEWS_API_KEY="YOUR_API_KEY"

Step 1: Get articles with their sentiment

import os
from datetime import date, timedelta

import requests

API_KEY = os.environ.get("WORLD_NEWS_API_KEY", "YOUR_API_KEY")
since = (date.today() - timedelta(days=7)).isoformat()

response = requests.get(
    "https://api.worldnewsapi.com/search-news",
    headers={"x-api-key": API_KEY},
    params={"entities": "ORG:Tesla", "language": "en", "earliest-publish-date": since, "number": 10},
    timeout=30,
)
response.raise_for_status()
for article in response.json()["news"]:
    score = article.get("sentiment")  # missing for articles in other languages than English and German
    print(f"{score:+.3f}" if score is not None else "   n/a", article["publish_date"], article["title"])

The entities filter matches the organization whatever name an article uses for it. Use text instead if you want a plain keyword match.

Example response (shortened), from the Search News docs (the docs example searches for earth quake):

{
  "offset": 0,
  "number": 10,
  "available": 83,
  "news": [
    {
      "id": 206030983,
      "title": "Nearly 30 aftershocks recorded around NJ quake epicenter since Friday",
      "url": "https://nypost.com/2024/04/06/us-news/nearly-30-aftershocks-recorded-around-nj-quake-epicenter/",
      "publish_date": "2024-04-06 22:44:18",
      "category": "environment",
      "language": "en",
      "source_country": "us",
      "sentiment": -0.545
    }
  ]
}

Step 2: Filter by sentiment

Use max-sentiment to get only negative coverage and min-sentiment for only positive coverage. Where you draw the line is your choice: the API gives you the score, not a label. A cheap trick: ask for 1 result and read available, the number of matching articles. Each count costs 1.01 points.

import os
import time
from datetime import date, timedelta

import requests

API_KEY = os.environ.get("WORLD_NEWS_API_KEY", "YOUR_API_KEY")
since = (date.today() - timedelta(days=7)).isoformat()


def count_matches(**extra):
    params = {"entities": "ORG:Tesla", "language": "en", "earliest-publish-date": since, "number": 1}
    params.update(extra)
    response = requests.get(
        "https://api.worldnewsapi.com/search-news",
        headers={"x-api-key": API_KEY},
        params=params,
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["available"]


negative = count_matches(**{"max-sentiment": -0.3})
time.sleep(1)  # free plan: 1 request per second
positive = count_matches(**{"min-sentiment": 0.3})
print(f"Last 7 days: {negative} clearly negative and {positive} clearly positive articles")

Step 3: Fetch all articles for an entity

This function pages through results 100 at a time, waits 1 second between requests and retries on 429. It sorts by publish time and sets both publish dates, which the API requires for that sort when there is no text (otherwise it limits the range to the last 31 days). Dates use the YYYY-MM-DD HH:MM:SS format from the parameter docs.

import os
import time

import requests

API_KEY = os.environ.get("WORLD_NEWS_API_KEY", "YOUR_API_KEY")
URL = "https://api.worldnewsapi.com/search-news"


def fetch_articles(entity, language, since, until, max_results=200):
    session = requests.Session()
    session.headers["x-api-key"] = API_KEY
    articles, offset, retries = [], 0, 0
    while len(articles) < max_results:
        params = {
            "entities": entity,
            "language": language,
            "earliest-publish-date": since,
            "latest-publish-date": until,
            "sort": "publish-time",
            "sort-direction": "ASC",
            "offset": offset,
            "number": min(100, max_results - len(articles)),
        }
        response = session.get(URL, params=params, timeout=30)
        if response.status_code == 429 and retries < 5:
            retries += 1
            time.sleep(2 ** retries)
            continue
        response.raise_for_status()  # 401, 402 and other errors stop here
        page = response.json()
        news = page.get("news", [])
        articles.extend(news)
        offset += len(news)
        if not news or offset >= page.get("available", 0):
            break
        time.sleep(1)  # free plan: 1 request per second
    return articles

Step 4: Aggregate daily sentiment per entity

Group the scores by the date part of publish_date and compute the count, the mean and the share of negative articles. Add this below the function from step 3:

from collections import defaultdict
from datetime import datetime, timedelta, timezone
from statistics import mean

MIN_ARTICLES = 5  # days with fewer articles are too noisy to read much into


def daily_sentiment(articles):
    by_day = defaultdict(list)
    for article in articles:
        score = article.get("sentiment")
        if score is not None:
            by_day[article["publish_date"][:10]].append(score)
    return {
        day: {
            "articles": len(scores),
            "mean": mean(scores),
            "negative_share": sum(score < 0 for score in scores) / len(scores),
        }
        for day, scores in sorted(by_day.items())
    }


now = datetime.now(timezone.utc)
since = (now - timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S")
until = now.strftime("%Y-%m-%d %H:%M:%S")
entities = ["ORG:Tesla", "ORG:Volkswagen"]

results = {entity: fetch_articles(entity, "en", since, until) for entity in entities}
for entity, articles in results.items():
    print(f"{entity}: {len(articles)} articles")
    for day, stats in daily_sentiment(articles).items():
        note = "" if stats["articles"] >= MIN_ARTICLES else "  (few articles)"
        print(f"  {day}  n={stats['articles']:3d}  mean={stats['mean']:+.3f}  "
              f"negative={stats['negative_share']:.0%}{note}")

For German coverage, call fetch_articles(entity, "de", since, until) and keep the results apart from the English ones, so you can see whether the two differ.

The script fetches fresh data on every run and keeps nothing. If you want to save the daily series to a database, note that the terms of use do not allow storing API data, including derived data such as these averages, without a separate written agreement; ask at [email protected] first.

Step 5: The same with pandas (optional)

If you already use pandas, build a DataFrame from results and let groupby do the work:

import pandas as pd

rows = [
    {"entity": entity, "day": article["publish_date"][:10], "sentiment": article.get("sentiment")}
    for entity, articles in results.items()
    for article in articles
]
df = pd.DataFrame(rows).dropna(subset=["sentiment"])
daily = df.groupby(["entity", "day"])["sentiment"].agg(["count", "mean"]).round(3)
print(daily)

by_entity = daily["mean"].unstack("entity")  # one row per day, one column per entity
print(by_entity)
print(by_entity.rolling(3, min_periods=1).mean().round(3))  # 3-day rolling mean

How to read the numbers

  • One score per article. The score describes the whole article, not the entity you filtered for. A gloomy market report that mentions Tesla once still counts with its overall tone.
  • Show the count next to the mean. The mean of a day with 3 articles can change a lot with a single story. Compare days with similar volume, or use the rolling mean.
  • Copies count separately. If several outlets publish the same story, each copy is one article. Remove duplicate titles if you want to count stories, not articles.
  • English and German only. Sentiment is computed for these 2 languages. Filter with language so other languages do not show up as gaps in your data.

Error handling

StatusWhat it meansWhat to do
401 UnauthorizedListed for every endpoint in the OpenAPI file; the docs say nothing more.Check the key and the x-api-key header name.
402 Payment RequiredOn the free plan, today's points are used up (quota docs).Fetch fewer entities or days, or wait for the reset at midnight UTC.
429 Too Many RequestsToo many requests per second or at once.The function in step 3 retries with growing delays. Do not fetch entities in parallel on the free plan.

What this guide costs

StepRequestsPoints
Step 1: 10 articles11.1
Step 2: 2 counts22.02
Steps 3 and 4: 2 entities, up to 200 articles eachup to 4up to 8
Step 5: reuses the data00
Totalup to 7about 11 of the free plan's 50 daily points

To track 10 entities every day with up to 100 articles each, plan for 10 requests and 20 points a day.

Next steps

Frequently asked questions

Which languages have sentiment scores?

English and German. World News API computes sentiment for articles in these 2 languages only, so set language=en or language=de when you analyze sentiment.

What does the sentiment score mean?

It is a number from -1 to 1: below 0 leans negative, above 0 leans positive. There is one score per article, and it describes the whole article.

Can I filter news by sentiment?

Yes. Search News accepts min-sentiment and max-sentiment, both in the range -1 to 1. For example, max-sentiment=-0.3 returns only clearly negative articles.

Is the sentiment score per entity?

No, it is per article. To track an entity, filter with the entities parameter, for example ORG:Tesla, and average the scores of the matching articles per day.

How far back can I analyze news sentiment?

The free plan covers the last month. The Reporter plan and higher give access to the archive, which starts on January 1, 2022.

Last updated November 22, 2026 by the World News API team. Spotted an error? Tell us at [email protected] or on Discord.

More from World News API

  • Compare news APIs
    World News API next to NewsAPI.org, NewsData.io, GNews, Mediastack and others.
  • Guides
    Step-by-step tutorials with working code.
  • Use cases
    AI agents, finance, media monitoring and research.
  • Documentation
    Every endpoint with parameters, examples and quotas.

Get a free API key