Skip to Content
While25SDK docs
ExamplesMonitors

News alerts for a watchlist

Sends a notice for each live news article on AAPL, MSFT or NVDA whose title contains one of your keywords, and on start backfills the last day's articles to the console so nothing from the morning is missed. With no news vendor configured it says so once and keeps running.

Sends a notice for each live news article on AAPL, MSFT or NVDA whose title contains one of your keywords, and on start backfills the last day's articles to the console so nothing from the morning is missed. With no news vendor configured it says so once and keeps running.

Shows: Monitor, @on.news on several symbols, news(symbols, start=, limit=) with .truncated / .errors, the NO_PROVIDER refusal, a Str input, absent article fields.

View on GitHub

monitors/news_alerts.py
"""News alerts for a watchlist

Sends a notice for each live news article on AAPL, MSFT or NVDA whose
title contains one of your keywords, and on start backfills the last day's
articles to the console so nothing from the morning is missed. With no news
vendor configured it says so once and keeps running.

Shows: Monitor, @on.news on several symbols, news(symbols, start=, limit=) with .truncated / .errors, the NO_PROVIDER refusal, a Str input, absent article fields.
"""
from datetime import date, timedelta

import while25
from while25 import Monitor, on
from while25.inputs import Str

SYMBOLS = ["EQ:US:AAPL", "EQ:US:MSFT", "EQ:US:NVDA"]


def keywords(text):
    """The comma-separated words of a setting, lower-cased, blanks dropped."""
    return [w.strip().lower() for w in text.split(",") if w.strip()]


def matches(article, words):
    """True when the title (or the excerpt, when sent) holds one of `words`.
    No words means every article."""
    text = (article["title"] + " " + article.get("excerpt", "")).lower()
    return not words or any(w in text for w in words)


class NewsAlerts(Monitor):
    id = "us_news_alerts"
    label = "News alerts"
    inputs = [Str("keywords", default="guidance, downgrade, upgrade, recall, SEC",
                  label="Alert on these words (comma-separated)")]

    def on_start(self, ctx):
        self.words = keywords(while25.params["keywords"])
        since = (date.today() - timedelta(days=1)).isoformat()
        try:
            rows = while25.news(SYMBOLS, start=since, limit=20)
        except while25.While25Error as e:
            if e.code != "NO_PROVIDER":
                raise
            while25.log("no news vendor is configured: the live lines will stay quiet", "warn")
            return
        for a in rows:
            if matches(a, self.words):
                while25.log(f"{a['symbol']} {a['title']} ({a.get('source', 'source not stated')})")
        if rows.truncated:
            while25.log("the backfill hit its page cap: older articles may exist")
        for key, how in rows.errors.items():
            while25.log(f"news for {key}: {how}", "warn")

    @on.news("EQ:US:AAPL")
    @on.news("EQ:US:MSFT")
    @on.news("EQ:US:NVDA")
    def article(self, ctx, article):
        if matches(article, self.words):
            while25.notify(article["title"], title=article["symbol"].split(":")[-1],
                           symbol=article["symbol"])