Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat: add StockTwits as a source, gated to ticker/crypto topics (#658)

Waqas Tiwanaa28668ad3033
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 92be236f..f55b09d3 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -90,6 +90,7 @@ The project-scoped file is useful for **intentional per-client setups**: drop a
| Reddit (public) | none (default); `SCRAPECREATORS_API_KEY` + `LAST30DAYS_REDDIT_BACKEND=scrapecreators` to pin SC primary with public fallback | always on; SC pin requires `SCRAPECREATORS_API_KEY` | yes |
| Hacker News | none | always on | yes |
| Polymarket | none | always on | yes |
+| StockTwits | none | auto-on for ticker/crypto topics only (gated by symbol detection); never registered for non-financial topics | yes (public API, ~200 req/hr per IP) |
| GitHub | `gh` CLI installed (uses your GitHub auth) | always on if `gh` present | yes |
| YouTube | `yt-dlp` CLI installed; `SCRAPECREATORS_API_KEY` adds a server-side transcript fallback used only when yt-dlp fails (429 / bot-gate) | always on if `yt-dlp` present; SC transcript fallback default-on when key set (no credit spent unless yt-dlp fails) | yes |
| YouTube comments | `SCRAPECREATORS_API_KEY` (default-on; suppress via `EXCLUDE_SOURCES=youtube_comments`) | top comments on the top ~3 videos by engagement | ~3 calls/run; 10K free calls |
diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.py
index a64a5d4f..569c2865 100644
--- a/skills/last30days/scripts/lib/normalize.py
+++ b/skills/last30days/scripts/lib/normalize.py
@@ -43,6 +43,7 @@ def normalize_source_items(
"tiktok": lambda s, i, idx, fd, td: _normalize_shortform_video(s, i, idx, fd, td, "TK", "TikTok post"),
"instagram": lambda s, i, idx, fd, td: _normalize_shortform_video(s, i, idx, fd, td, "IG", "Instagram reel"),
"hackernews": _normalize_hackernews,
+ "stocktwits": _normalize_stocktwits,
"bluesky": lambda s, i, idx, fd, td: _normalize_microblog(s, i, idx, fd, td, "BS", "Bluesky post"),
"truthsocial": lambda s, i, idx, fd, td: _normalize_microblog(s, i, idx, fd, td, "TS", "Truth Social post"),
"threads": lambda s, i, idx, fd, td: _normalize_microblog(s, i, idx, fd, td, "TH", "Threads post"),
@@ -187,6 +188,32 @@ def _source_item(
)
+def _normalize_stocktwits(
+ source: str,
+ item: dict[str, Any],
+ index: int,
+ from_date: str,
+ to_date: str,
+) -> schema.SourceItem:
+ meta = item.get("metadata") or {}
+ return _source_item(
+ item_id=str(item.get("id") or f"ST{index + 1}"),
+ source=source,
+ title=str(item.get("title") or ""),
+ body=str(item.get("snippet") or ""),
+ url=str(item.get("url") or ""),
+ author=str(item.get("author") or "") or None,
+ container=str(meta.get("symbol") or "") or None,
+ published_at=item.get("date"),
+ date_confidence=_date_confidence(item, from_date, to_date, default="high"),
+ engagement=item.get("engagement") or {},
+ relevance_hint=item.get("relevance", 0.7),
+ why_relevant=str(item.get("why_relevant") or ""),
+ snippet=str(item.get("snippet") or "")[:400],
+ metadata=meta, # carries sentiment + symbol-level bull/bear aggregate
+ )
+
+
def _normalize_reddit(
source: str,
item: dict[str, Any],
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 4e622a6c..a1a58db6 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -42,6 +42,7 @@ from . import (
schema,
signals,
snippet,
+ stocktwits,
techmeme,
threads,
tiktok,
@@ -71,7 +72,7 @@ SEARCH_ALIAS = {
"xquik": "x", # xquik is a backend of the single "x" source, not its own source
}
-MAX_SOURCE_FETCHES: dict[str, int] = {"x": 2, "jobs": 1, "linkedin": 1}
+MAX_SOURCE_FETCHES: dict[str, int] = {"x": 2, "jobs": 1, "linkedin": 1, "stocktwits": 1}
# Per-handle result caps for the X handle-search lanes. The FROM lane (the
# subject's own timeline) is the single best source for a person topic, so it
@@ -148,6 +149,9 @@ def available_sources(
if which("yt-dlp") or env.is_youtube_sc_available(config):
available.append("youtube")
available.extend(["hackernews", "polymarket"])
+ # StockTwits is gated to ticker/crypto topics only (flag set in run()).
+ if config.get("_financial_topic"):
+ available.append("stocktwits")
# GitHub is reachable via the unauthenticated REST tier too, so it is
# available even without a token/gh CLI (a token only raises rate limits).
available.append("github")
@@ -334,6 +338,11 @@ def run(
requested_sources = normalize_requested_sources(requested_sources)
from_date, to_date = dates.get_date_range(lookback_days, as_of_date=as_of_date)
+ # Gate StockTwits to ticker/crypto topics. Single chokepoint: when False,
+ # available_sources() never registers stocktwits, so the planner can't
+ # assign it (eligible_sources = available ∩ capabilities).
+ config["_financial_topic"] = stocktwits.is_financial_topic(topic)
+
if mock:
runtime = providers.mock_runtime(config, depth)
reasoning_provider = None
@@ -1475,6 +1484,12 @@ def _retrieve_stream(
if source == "hackernews":
result = hackernews.search_hackernews(subquery.search_query, from_date, to_date, depth=depth)
return hackernews.parse_hackernews_response(result, query=subquery.search_query), {}
+ if source == "stocktwits":
+ # Pass raw_topic so symbol detection sees the full topic, not the
+ # narrowed per-subquery search_query (same rationale as reddit).
+ result = stocktwits.search_stocktwits(
+ raw_topic or topic or subquery.search_query, from_date, to_date, depth=depth)
+ return stocktwits.parse_stocktwits_response(result, query=subquery.search_query), {}
if source == "digg":
result = digg.search_digg(subquery.search_query, from_date, to_date, depth=depth)
items = digg.parse_digg_response(result, query=subquery.search_query)
diff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.py
index e2701def..312abf9f 100644
--- a/skills/last30days/scripts/lib/planner.py
+++ b/skills/last30days/scripts/lib/planner.py
@@ -41,11 +41,11 @@ SOURCE_PRIORITY = {
"factual": ["hackernews", "reddit", "x", "youtube"],
"product": ["jobs", "youtube", "reddit", "x", "tiktok", "hackernews"],
"concept": ["hackernews", "reddit", "x", "youtube"],
- "opinion": ["reddit", "x", "youtube", "hackernews"],
+ "opinion": ["reddit", "x", "stocktwits", "youtube", "hackernews"],
"how_to": ["youtube", "reddit", "x", "hackernews"],
"comparison": ["reddit", "x", "hackernews", "youtube"],
- "breaking_news": ["x", "reddit", "hackernews", "youtube", "polymarket"],
- "prediction": ["polymarket", "x", "hackernews", "reddit", "youtube"],
+ "breaking_news": ["x", "stocktwits", "reddit", "hackernews", "youtube", "polymarket"],
+ "prediction": ["polymarket", "stocktwits", "x", "hackernews", "reddit", "youtube"],
}
SOURCE_LIMITS = {
"quick": {
@@ -77,6 +77,7 @@ SOURCE_CAPABILITIES = {
"bluesky": {"discussion", "social"},
"truthsocial": {"discussion", "social"},
"polymarket": {"market"},
+ "stocktwits": {"social", "market", "finance_social"},
"digg": {"discussion", "social", "link"},
"arxiv": {"reference", "analysis", "link"},
"techmeme": {"discussion", "link", "reference"},
diff --git a/skills/last30days/scripts/lib/stocktwits.py b/skills/last30days/scripts/lib/stocktwits.py
new file mode 100644
index 00000000..71c3cc2d
--- /dev/null
+++ b/skills/last30days/scripts/lib/stocktwits.py
@@ -0,0 +1,303 @@
+"""StockTwits source for last30days — ticker/crypto topics only.
+
+StockTwits is a cashtag-native social network for traders. Every message can
+carry a self-reported Bullish/Bearish tag, which makes it uniquely good at one
+thing the other sources can't quantify: a sentiment *ratio* and retail *volume*
+on a specific symbol.
+
+GATING: this source is only meaningful for financial topics. `detect_symbols()`
+and `is_financial_topic()` are the gate — the pipeline must NOT register
+stocktwits for a non-ticker topic (see INTEGRATION.md, step 3). Treat the output
+as a direction/volume signal, never as analysis: StockTwits skews retail and
+promotional, sentiment tags are self-reported, and bot/pump noise is common.
+
+API: public, no auth. Symbol stream + symbol search endpoints. Unauthenticated
+quota is ~200 requests/hour and is rate-limited per IP — keep pagination small.
+Respect StockTwits' API terms if this is ever shipped beyond personal use.
+
+NOTE: uses raw urllib rather than the shared `from . import http` helper.
+Every call is wrapped in try/except and degrades to a partial/empty result, but
+switching to the shared helper (429 Retry-After, retry budget, backoff) is a
+known follow-up to match siblings like hackernews.py.
+"""
+
+from __future__ import annotations
+
+import datetime
+import json
+import re
+import sys
+import time
+import urllib.parse
+import urllib.request
+from typing import Any
+
+_UA = "Mozilla/5.0 (last30days stocktwits source)"
+_STREAM_URL = "https://api.stocktwits.com/api/2/streams/symbol/{symbol}.json"
+_SEARCH_URL = "https://api.stocktwits.com/api/2/search/symbols.json"
+
+# Topic must look financial before we even try to resolve a symbol. This is the
+# coarse gate; symbol resolution is the fine gate.
+_FINANCE_HINTS = re.compile(
+ # Unambiguous finance vocabulary only. Bare "share/token/coin/bull/bear"
+ # were removed: they misfire on general topics ("share files", "token
+ # limits", "coin collecting", "bear attacks") and would inject stock chatter
+ # into non-financial runs.
+ r"\b(stock|stocks|ticker|cashtag|equit(?:y|ies)|price target|"
+ r"earnings|premarket|pre-?market|after\s?hours|dividend|valuation|"
+ r"crypto|altcoin|defi|market cap|bullish|bearish|"
+ # Unambiguous crypto names so "bitcoin price" gates without a cashtag.
+ # Short aliases (eth, sol, ada, doge, ripple) stay OUT of the gate: they
+ # collide with everyday topics (ETH Zurich, ADA compliance, doge memes);
+ # they still resolve via _CRYPTO_ALIASES once the gate fires another way.
+ r"bitcoin|btc|ethereum|solana|dogecoin|cardano|xrp|"
+ r"\$[A-Za-z]{1,5}(?:\.[A-Z])?)\b",
+ re.IGNORECASE,
+)
+_CASHTAG = re.compile(r"\$([A-Za-z]{1,5}(?:\.[A-Z])?)\b")
+
+# A small built-in crypto map so we don't burn a symbol-search call on the
+# obvious ones. StockTwits uses the `.X` suffix for crypto symbols.
+_CRYPTO_ALIASES = {
+ "bitcoin": "BTC.X", "btc": "BTC.X",
+ "ethereum": "ETH.X", "eth": "ETH.X",
+ "solana": "SOL.X", "sol": "SOL.X",
+ "dogecoin": "DOGE.X", "doge": "DOGE.X",
+ "ripple": "XRP.X", "xrp": "XRP.X",
+ "cardano": "ADA.X", "ada": "ADA.X",
+}
+
+
+def _log(msg: str) -> None:
+ try:
+ from . import log as _enginelog
+ _enginelog.source_log("StockTwits", msg, tty_only=False)
+ except Exception: # standalone / outside package
+ print(f"[StockTwits] {msg}", file=sys.stderr)
+
+
+def _get_json(url: str, timeout: int = 20) -> dict[str, Any]:
+ req = urllib.request.Request(url, headers={"User-Agent": _UA})
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return json.load(resp)
+
+
+# --------------------------------------------------------------------------- #
+# Gating + symbol resolution #
+# --------------------------------------------------------------------------- #
+
+def is_financial_topic(topic: str) -> bool:
+ """Coarse gate: does the topic look like it's about a tradeable asset?"""
+ return bool(_CASHTAG.search(topic) or _FINANCE_HINTS.search(topic))
+
+
+def detect_symbols(topic: str, *, resolve: bool = True, max_symbols: int = 2) -> list[str]:
+ """Resolve a topic to StockTwits symbols. Returns [] for non-financial topics.
+
+ Order of resolution:
+ 1. Explicit cashtags in the topic ($NOW, $BTC.X) — trusted as-is.
+ 2. Crypto name aliases (bitcoin -> BTC.X).
+ 3. StockTwits symbol-search API for a company/product name, but ONLY if the
+ topic also tripped the finance gate (so "Apple pie" never resolves AAPL).
+
+ `resolve=False` skips the network call (useful for the cheap gate check).
+ """
+ found: list[str] = []
+
+ for m in _CASHTAG.finditer(topic):
+ sym = m.group(1).upper()
+ if sym not in found:
+ found.append(sym)
+
+ lowered = topic.lower()
+ for alias, sym in _CRYPTO_ALIASES.items():
+ if re.search(rf"\b{re.escape(alias)}\b", lowered) and sym not in found:
+ found.append(sym)
+
+ if found:
+ return found[:max_symbols]
+
+ # No explicit symbol. Only hit the network if the topic looks financial.
+ if not resolve or not is_financial_topic(topic):
+ return []
+
+ # Strip finance noise words so the search query is just the entity name.
+ name = re.sub(
+ r"\b(stock|stocks|shares?|price|ticker|earnings|forecast|crypto|"
+ r"token|coin|news|today|now)\b",
+ "", topic, flags=re.IGNORECASE,
+ ).strip()
+ if not name:
+ return []
+ try:
+ url = _SEARCH_URL + "?" + urllib.parse.urlencode({"q": name})
+ data = _get_json(url)
+ for result in data.get("results", []):
+ sym = (result.get("symbol") or "").upper()
+ if sym and sym not in found:
+ found.append(sym)
+ if len(found) >= max_symbols:
+ break
+ if found:
+ _log(f"Resolved '{name}' -> {found}")
+ except Exception as e: # noqa: BLE001 — network/parse, degrade gracefully
+ _log(f"symbol search failed for '{name}': {e}")
+ return found[:max_symbols]
+
+
+# --------------------------------------------------------------------------- #
+# Fetch + parse #
+# --------------------------------------------------------------------------- #
+
+_DEPTH = {"quick": 30, "default": 60, "deep": 120}
+
+
+def search_stocktwits(
+ topic_or_symbol: str,
+ from_date: str | None = None,
+ to_date: str | None = None,
+ *,
+ depth: str = "default",
+) -> dict[str, Any]:
+ """Fetch the symbol stream for the topic. Paginates by cursor up to `depth`.
+
+ Accepts either a raw topic (resolved via detect_symbols) or an explicit
+ symbol. Returns {"messages": [...], "symbols": [...], "watchlist": int}.
+ """
+ symbols = (
+ [topic_or_symbol.lstrip("$").upper()]
+ if _CASHTAG.fullmatch("$" + topic_or_symbol.lstrip("$"))
+ else detect_symbols(topic_or_symbol)
+ )
+ if not symbols:
+ return {"messages": [], "symbols": [], "error": "no symbol resolved"}
+
+ symbol = symbols[0] # primary symbol drives the stream
+ target = _DEPTH.get(depth, 60)
+ messages: list[dict[str, Any]] = []
+ watchlist = None
+ cursor_max = None
+ try:
+ while len(messages) < target:
+ url = _STREAM_URL.format(symbol=urllib.parse.quote(symbol))
+ if cursor_max:
+ url += f"?max={cursor_max}"
+ data = _get_json(url)
+ if watchlist is None:
+ watchlist = (data.get("symbol") or {}).get("watchlist_count")
+ batch = data.get("messages", [])
+ if not batch:
+ break
+ messages.extend(batch)
+ cursor = data.get("cursor", {})
+ if not cursor.get("more") or not cursor.get("max"):
+ break
+ cursor_max = cursor["max"]
+ time.sleep(0.8) # be polite to the unauth quota
+ except Exception as e: # noqa: BLE001
+ _log(f"stream fetch failed for {symbol}: {e}")
+ return {"messages": messages, "symbols": symbols, "error": str(e)}
+
+ messages = _filter_by_date(messages, from_date, to_date)
+ _log(f"{symbol}: {len(messages)} messages (watchlist {watchlist})")
+ return {"messages": messages, "symbols": symbols, "watchlist": watchlist}
+
+
+def _filter_by_date(messages: list[dict], from_date: str | None, to_date: str | None) -> list[dict]:
+ if not (from_date or to_date):
+ return messages
+ out = []
+ for m in messages:
+ d = (m.get("created_at") or "")[:10]
+ if from_date and d and d < from_date:
+ continue
+ if to_date and d and d > to_date:
+ continue
+ out.append(m)
+ return out
+
+
+def parse_stocktwits_response(response: dict[str, Any], query: str = "") -> list[dict[str, Any]]:
+ """Normalize the stream into engine-style item dicts (same keys as HN/Reddit).
+
+ Each item carries metadata.sentiment in {"Bullish","Bearish",None} and the
+ symbol-level bull/bear aggregate so synthesis can cite the ratio.
+ """
+ messages = response.get("messages", [])
+ symbols = response.get("symbols", [])
+ agg = aggregate_sentiment(messages)
+ items: list[dict[str, Any]] = []
+ for i, m in enumerate(messages):
+ user = m.get("user") or {}
+ username = user.get("username") or "unknown"
+ body = (m.get("body") or "").strip()
+ sentiment = ((m.get("entities") or {}).get("sentiment") or {}).get("basic")
+ likes = (m.get("likes") or {}).get("total", 0) or 0
+ reshares = (m.get("reshares") or {}).get("reshared_count", 0) or 0
+ followers = user.get("followers", 0) or 0
+ # Relevance: cashtag-native source, so on-symbol is a near-given. Nudge
+ # by author reach + a tagged-sentiment bonus (tagged posts are higher
+ # intent than chatter).
+ relevance = min(1.0, 0.7 + (0.1 if sentiment else 0.0) + min(0.2, followers / 50000))
+ items.append({
+ "id": str(m.get("id") or f"ST{i+1}"),
+ "title": body[:120] or f"${symbols[0] if symbols else ''} post",
+ "url": f"https://stocktwits.com/{username}/message/{m.get('id')}",
+ "author": username,
+ "date": (m.get("created_at") or "")[:10] or None,
+ "engagement": {"likes": likes, "reshares": reshares, "followers": followers},
+ "relevance": round(relevance, 2),
+ "why_relevant": f"StockTwits ${symbols[0] if symbols else ''} post"
+ + (f" tagged {sentiment}" if sentiment else ""),
+ "snippet": body[:400],
+ "metadata": {
+ "sentiment": sentiment,
+ "symbol": symbols[0] if symbols else None,
+ "sentiment_aggregate": agg, # same dict on every item; cheap, lets synthesis cite it
+ "watchlist": response.get("watchlist"),
+ },
+ })
+ return items
+
+
+def aggregate_sentiment(messages: list[dict[str, Any]]) -> dict[str, Any]:
+ """Bull/bear counts + ratio over the sentiment-tagged subset."""
+ bull = bear = 0
+ for m in messages:
+ s = ((m.get("entities") or {}).get("sentiment") or {}).get("basic")
+ if s == "Bullish":
+ bull += 1
+ elif s == "Bearish":
+ bear += 1
+ tagged = bull + bear
+ return {
+ "bullish": bull,
+ "bearish": bear,
+ "untagged": len(messages) - tagged,
+ "pct_bullish": round(100 * bull / tagged) if tagged else None,
+ "sample": len(messages),
+ }
+
+
+# --------------------------------------------------------------------------- #
+# Standalone CLI (ad-hoc use today, before any engine wiring) #
+# python3 stocktwits.py "ServiceNow stock" #
+# --------------------------------------------------------------------------- #
+if __name__ == "__main__":
+ topic = " ".join(sys.argv[1:]) or "$NOW"
+ if not is_financial_topic(topic) and not detect_symbols(topic, resolve=False):
+ print(f"Not a ticker/crypto topic — skipping StockTwits: {topic!r}")
+ raise SystemExit(0)
+ today = datetime.date.today()
+ since = (today - datetime.timedelta(days=30)).isoformat()
+ resp = search_stocktwits(topic, from_date=since, depth="default")
+ if resp.get("error") and not resp.get("messages"):
+ print("error:", resp["error"]); raise SystemExit(1)
+ items = parse_stocktwits_response(resp, query=topic)
+ agg = aggregate_sentiment(resp["messages"])
+ print(f"symbol(s): {resp.get('symbols')} | watchlist {resp.get('watchlist')}")
+ print(f"sentiment: {agg['bullish']} bull / {agg['bearish']} bear "
+ f"({agg['pct_bullish']}% bullish of tagged) over {agg['sample']} msgs")
+ for it in sorted(items, key=lambda x: x["engagement"]["likes"], reverse=True)[:8]:
+ s = it["metadata"]["sentiment"] or "-"
+ print(f" [{it['engagement']['likes']}♥ {s}] @{it['author']}: {it['snippet'][:120]}")
diff --git a/tests/test_stocktwits.py b/tests/test_stocktwits.py
new file mode 100644
index 00000000..2d8114b0
--- /dev/null
+++ b/tests/test_stocktwits.py
@@ -0,0 +1,149 @@
+"""Tests for stocktwits.py - StockTwits source (ticker/crypto topics only).
+
+All hermetic: symbol-search and stream HTTP calls are patched, so no network.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+from lib import stocktwits, normalize, planner, pipeline
+
+
+# === Gating: is_financial_topic / detect_symbols ===
+
+def test_cashtag_is_financial():
+ assert stocktwits.is_financial_topic("$NVDA earnings")
+ assert stocktwits.detect_symbols("$NVDA earnings", resolve=False) == ["NVDA"]
+
+
+def test_crypto_alias_resolves_with_dot_x_suffix():
+ assert stocktwits.detect_symbols("bitcoin price", resolve=False) == ["BTC.X"]
+ assert stocktwits.detect_symbols("should I buy ethereum", resolve=False) == ["ETH.X"]
+
+
+def test_non_financial_topic_resolves_to_nothing():
+ # The whole point of the gate: a person/recipe must never resolve a ticker.
+ assert not stocktwits.is_financial_topic("Kanye West")
+ assert stocktwits.detect_symbols("Kanye West", resolve=True) == []
+ assert stocktwits.detect_symbols("Apple pie recipe", resolve=True) == []
+
+
+def test_general_topics_with_ambiguous_words_do_not_trip_the_gate():
+ # Regression guard for the tightened _FINANCE_HINTS: these everyday phrases
+ # contain words that USED to trip the gate (share/token/coin/bear) and must
+ # never register stocktwits for a non-financial run.
+ for topic in (
+ "how to share files on iPhone",
+ "Claude token limits",
+ "coin collecting for beginners",
+ "bear attacks in Yellowstone",
+ "bull riding championship",
+ ):
+ assert not stocktwits.is_financial_topic(topic), topic
+ assert stocktwits.detect_symbols(topic, resolve=False) == [], topic
+
+
+def test_finance_vocabulary_still_trips_the_gate():
+ for topic in (
+ "bullish on NVDA earnings",
+ "TSLA stock forecast",
+ "best dividend stocks",
+ "altcoin season predictions",
+ "bitcoin price",
+ ):
+ assert stocktwits.is_financial_topic(topic), topic
+
+
+def test_name_resolution_only_fires_for_financial_topics():
+ # "Apple pie recipe" trips no finance hint -> no symbol-search call at all.
+ with patch.object(stocktwits, "_get_json") as mock_get:
+ assert stocktwits.detect_symbols("Apple pie recipe", resolve=True) == []
+ mock_get.assert_not_called()
+
+ # "ServiceNow stock" trips the gate -> symbol search runs and resolves.
+ with patch.object(stocktwits, "_get_json", return_value={"results": [{"symbol": "NOW"}]}) as mock_get:
+ assert stocktwits.detect_symbols("ServiceNow stock", resolve=True) == ["NOW"]
+ mock_get.assert_called_once()
+
+
+# === Parsing + sentiment aggregation ===
+
+def _msg(mid, user, body, sentiment=None, likes=0, created="2026-06-20T12:00:00Z"):
+ m = {
+ "id": mid,
+ "body": body,
+ "created_at": created,
+ "user": {"username": user, "followers": 1000},
+ "likes": {"total": likes},
+ }
+ if sentiment:
+ m["entities"] = {"sentiment": {"basic": sentiment}}
+ return m
+
+
+def _response():
+ return {
+ "symbols": ["NOW"],
+ "watchlist": 41000,
+ "messages": [
+ _msg(1, "alice", "$NOW buy the dip", "Bullish", likes=5),
+ _msg(2, "bob", "$NOW going to zero", "Bearish", likes=2),
+ _msg(3, "carol", "$NOW holding", None, likes=0),
+ ],
+ }
+
+
+def test_aggregate_sentiment_counts_and_ratio():
+ agg = stocktwits.aggregate_sentiment(_response()["messages"])
+ assert agg["bullish"] == 1
+ assert agg["bearish"] == 1
+ assert agg["untagged"] == 1
+ assert agg["pct_bullish"] == 50
+ assert agg["sample"] == 3
+
+
+def test_aggregate_sentiment_no_tagged_messages():
+ agg = stocktwits.aggregate_sentiment([_msg(1, "x", "$NOW", None)])
+ assert agg["pct_bullish"] is None # no division by zero
+
+
+def test_parse_builds_well_formed_items():
+ items = stocktwits.parse_stocktwits_response(_response(), query="ServiceNow")
+ assert len(items) == 3
+ first = items[0]
+ assert first["url"] == "https://stocktwits.com/alice/message/1"
+ assert first["author"] == "alice"
+ assert first["metadata"]["sentiment"] == "Bullish"
+ assert first["metadata"]["symbol"] == "NOW"
+ # The bull/bear aggregate rides on every item so synthesis can cite the ratio.
+ assert first["metadata"]["sentiment_aggregate"]["pct_bullish"] == 50
+ assert first["engagement"]["likes"] == 5
+
+
+# === Normalize wiring ===
+
+def test_normalizer_registered_and_maps_fields():
+ items = stocktwits.parse_stocktwits_response(_response(), query="ServiceNow")
+ normalized = normalize.normalize_source_items(
+ "stocktwits", items, from_date="2026-06-01", to_date="2026-06-30")
+ assert len(normalized) == 3
+ item = normalized[0]
+ assert item.source == "stocktwits"
+ assert item.container == "NOW" # symbol -> container
+ assert item.author == "alice"
+ assert item.metadata["sentiment"] == "Bullish"
+
+
+# === Planner + pipeline gate ===
+
+def test_planner_capability_and_priority():
+ assert planner.SOURCE_CAPABILITIES["stocktwits"] == {"social", "market", "finance_social"}
+ assert "stocktwits" in planner.SOURCE_PRIORITY["breaking_news"]
+ assert "stocktwits" in planner.SOURCE_PRIORITY["prediction"]
+
+
+def test_pipeline_availability_is_gated_by_financial_flag():
+ assert "stocktwits" in pipeline.available_sources({"_financial_topic": True})
+ assert "stocktwits" not in pipeline.available_sources({"_financial_topic": False})
+ assert "stocktwits" not in pipeline.available_sources({}) # default off