9fin 1.3 News: keeping a feed current

APIs used in this notebook

APIVersionEndpoints
News & Content v20.3.41GET /v2/news/headlines
Before you start

Run notebook 0.1 first; it provides the access token and the api_get helper that every call below uses.

Sample output

Every output on this page is a static sample. The results below were captured from a live run in October 2026 and are reproduced here so the page reads without credentials. Figures, article titles, identifiers and API versions were current that day and will have moved on since. Run the notebook yourself for live data.

You have a feed from notebook 1.2, or a list of companies from notebook 0.2. This notebook keeps it up to date: new articles, and articles you already hold that we have since amended.

Why the feed order decides the design

Headlines come back ordered by updated_at, newest first. Not by publication date.

That ordering decides the whole design. When we amend a story, the amended version returns to the top of the feed. So a newly published article and a two year old one corrected this morning arrive in the same place, and a single read from the top catches both.

since and until, by contrast, filter on the publication date. They are right for backfilling a period and wrong for staying current, because a correction to an old article falls outside any recent window.

So the pattern is: remember the highest updated_at you have processed, read from the top of the feed until you reach it, stop.

%run "9fin 0.1 Authentication - getting a token.ipynb"

import json, pathlib, datetime
import pandas as pd
pd.set_option("display.max_colwidth", 120)

First, see the ordering for yourself:

recent = api_get("/v2/news/headlines", source_type="9fin", limit=200)["items"]

all(a["updated_at"] >= b["updated_at"] for a, b in zip(recent, recent[1:]))

Sample output, captured October 2026. Static snapshot, not live data.

True

And how often the two dates differ, which is how much a publication-date window would miss:

amended = [i for i in recent if i["published_at"][:10] != i["updated_at"][:10]]

len(amended), amended[0]["published_at"][:10], amended[0]["updated_at"][:10]

Sample output, captured October 2026. Static snapshot, not live data.

(20, '2026-10-28', '2026-10-29')

A good share of the most recent feed was published on an earlier day. Some of those gaps are years wide.

Defining the universe

Anything the headlines endpoint filters on will do. This is the distressed desk from notebook 1.2.

UNIVERSE = {"source_type": "9fin", "region": "Europe",
            "content_tags__in": "9fin-Distressed,9fin-Liability Management (LME)"}

The state you keep

Two things, and they fit in a small JSON file.

mark is the highest updated_at you have processed. The poll stops when it reaches it.

seen maps an article id to the updated_at you last held for it. That is what distinguishes a genuinely new article from one you already have that has changed.

STATE = pathlib.Path("cache/universe_state.json")
STATE.parent.mkdir(exist_ok=True)

state = json.loads(STATE.read_text()) if STATE.exists() else {"mark": "", "seen": {}}
len(state["seen"]), state["mark"] or "not set"

Sample output, captured October 2026. Static snapshot, not live data.

(174, '2026-10-21T10:03:55.929615')

Seeding it the first time

On a first run there is nothing to compare against, so fill the state from some history. This is the one place since and until are the right tool, because you are selecting a period of publication rather than of change.

In a running job you seed once. Here the cells below rebuild the state as it stood three days ago on every run, so the poll always has three days of real movement to classify and the delta below is never empty.

def walk_headlines(**filters):
    """Every headline matching a filter, following the cursor."""
    out, cursor = [], None
    while True:
        page = api_get("/v2/news/headlines", **filters, limit=200,
                       **({"cursor": cursor} if cursor else {}))
        out += page["items"]
        cursor = page.get("next_cursor")
        if not cursor:
            return out
ago = lambda days: (datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
                    - datetime.timedelta(days=days)).isoformat()

MARK = ago(3)

Each backfilled article is recorded at min(updated_at, MARK), not at its current updated_at. Three days ago you held the article, but you did not hold any amendment we have made to it since. Capping the stored timestamp at the mark says exactly that, and it is what lets the poll below tell a genuine amendment from an article you already have unchanged.

history = walk_headlines(**UNIVERSE, since=ago(45)[:10], until=MARK[:10])
state = {"mark": MARK, "seen": {i["uuid"]: min(i["updated_at"], MARK) for i in history}}

len(state["seen"]), state["mark"][:19]

Sample output, captured October 2026. Static snapshot, not live data.

(167, '2026-10-26T10:06:33')

The poll

Read from the top, stop at the mark. Everything above it is unprocessed; nothing below it can have changed, because the feed is ordered by exactly that field.

In steady use this is a single call.

def poll(mark, max_pages=20):
    """Headlines updated since `mark`, newest first."""
    fresh, cursor = [], None
    for _ in range(max_pages):
        page = api_get("/v2/news/headlines", **UNIVERSE, limit=200,
                       **({"cursor": cursor} if cursor else {}))
        for item in page["items"]:
            if item["updated_at"] <= mark:
                return fresh
            fresh.append(item)
        cursor = page.get("next_cursor")
        if not cursor:
            return fresh
    return fresh
fresh = poll(state["mark"])

len(fresh)

Sample output, captured October 2026. Static snapshot, not live data.

26

New, amended, or already held

Compare each result against seen:

  • new, an id you have never met
  • amended, an id you hold, coming back with a newer timestamp. This is the one to surface separately, because the story you filed yesterday may now say something different
  • already held, an id at the same timestamp

The third case cannot appear in this run. The poll returns only what changed after the mark, and the rebuilt state caps every held timestamp at the mark, so each result is necessarily new or amended. In a running job, where the mark and seen both carry real timestamps from the last poll, the same comparison does throw up the occasional unchanged duplicate, which is why the branch is there.

def status(item):
    previous = state["seen"].get(item["uuid"])
    return "new" if previous is None else "amended" if item["updated_at"] > previous else "already held"

delta = pd.DataFrame([{"status": status(i), "published": i["published_at"][:10],
                       "updated": i["updated_at"][:16], "title": i["title"][:58]} for i in fresh])

delta["status"].value_counts().to_dict()

Sample output, captured October 2026. Static snapshot, not live data.

{'new': 25, 'amended': 1}

The amended rows are the ones to look at: articles published days or years ago that we have since revised, which a publication-date window would never have returned.

delta[delta["status"] == "amended"]

Sample output, captured October 2026. Static snapshot, not live data.

statuspublishedupdatedtitle
amended2026-10-202026-10-26T11:13Term time — The financial woes of UK universities (9fin)

Then record what you processed and move the mark forward:

state["seen"].update({i["uuid"]: i["updated_at"] for i in fresh})
state["mark"] = max([state["mark"], *(i["updated_at"] for i in fresh)])
STATE.write_text(json.dumps(state))

len(state["seen"]), state["mark"][:19]

Sample output, captured October 2026. Static snapshot, not live data.

(192, '2026-10-29T09:42:24')

Following companies instead of tags

A universe can equally be a list of companies from notebook 0.2, and the endpoint filters on them directly: nf_ids__in takes up to ten entity ids and returns anything referencing any of them. The match is on identifiers, never on the name appearing in the text, so it does not drift the way a keyword search would.

WATCHLIST = {"nf_ent_e276f5f7d33f45a0a6fb67212c52c2c5": "First Brands",
             "nf_ent_df4aa6984c5e4d69bac1b8809cb8b6b2": "Iceland",
             "nf_ent_8241128f33154e4cb95848c6d4f80cc8": "Ardagh"}
watched = walk_headlines(nf_ids__in=",".join(WATCHLIST), since=ago(30)[:10])

len(watched)

Sample output, captured October 2026. Static snapshot, not live data.

18

The server does the selecting, so you pay for the articles you want rather than filtering a month of everything on your own machine. Which company each one names still has to be read off the entities block, because an article can reference several.

def named_in(article):
    """Which watchlist companies this headline names."""
    ids = {(article["entities"].get("main") or {}).get("nf_id")} \
          | {e["nf_id"] for e in article["entities"].get("additional", [])}
    return sorted(WATCHLIST[i] for i in ids & WATCHLIST.keys())
pd.DataFrame([{"updated": a["updated_at"][:16], "companies": ", ".join(named_in(a)),
               "title": a["title"][:58]} for a in watched])

Over ten companies, run a poll per batch of ten and merge the results. A watchlist universe then slots into exactly the same mark and seen machinery as a tag universe: put nf_ids__in in UNIVERSE and everything above this section works unchanged.

How often to poll

A poll is one call whenever fewer than 200 articles in your universe have changed, which for a desk feed is nearly always. So choose the interval from how quickly you need to react, not from cost.

For scale: we published an average of 44 articles a day across all our own coverage in a representative month, with a busiest day of 71. A desk sees a fraction of that. Five or fifteen minutes keeps you close to real time and sits well inside the 100 calls a minute the News API allows.

Running it unattended

The loop is three lines, and it is idempotent. If a run fails or the machine restarts, the next one picks up from the mark and nothing is missed or handled twice.

fresh = poll(state["mark"])
# hand `fresh` to your own destination here
state["seen"].update({i["uuid"]: i["updated_at"] for i in fresh})
state["mark"] = max([state["mark"], *(i["updated_at"] for i in fresh)])

Two refinements for production. Move the mark forward only after the batch has been handled successfully, so a failure downstream retries rather than skips. And trim seen to the period you care about, because it grows.

The polling contract

the feed is ordered by updated_atone read from the top catches new and amended alike
since and until filter on publicationright for backfill, wrong for staying current
mark plus seenthe whole state a poller needs

Any uuid here goes to notebook 1.1 to read in full, or to notebook 2.2 to reach the bond a story is about.