| 1 | """StockTwits source for last30days — ticker/crypto topics only. |
| 2 | |
| 3 | StockTwits is a cashtag-native social network for traders. Every message can |
| 4 | carry a self-reported Bullish/Bearish tag, which makes it uniquely good at one |
| 5 | thing the other sources can't quantify: a sentiment *ratio* and retail *volume* |
| 6 | on a specific symbol. |
| 7 | |
| 8 | GATING: this source is only meaningful for financial topics. `detect_symbols()` |
| 9 | and `is_financial_topic()` are the gate — the pipeline must NOT register |
| 10 | stocktwits for a non-ticker topic (see INTEGRATION.md, step 3). Treat the output |
| 11 | as a direction/volume signal, never as analysis: StockTwits skews retail and |
| 12 | promotional, sentiment tags are self-reported, and bot/pump noise is common. |
| 13 | |
| 14 | API: public, no auth. Symbol stream + symbol search endpoints. Unauthenticated |
| 15 | quota is ~200 requests/hour and is rate-limited per IP — keep pagination small. |
| 16 | Respect StockTwits' API terms if this is ever shipped beyond personal use. |
| 17 | |
| 18 | NOTE: uses raw urllib rather than the shared `from . import http` helper. |
| 19 | Every call is wrapped in try/except and degrades to a partial/empty result, but |
| 20 | switching to the shared helper (429 Retry-After, retry budget, backoff) is a |
| 21 | known follow-up to match siblings like hackernews.py. |
| 22 | """ |
| 23 | |
| 24 | from __future__ import annotations |
| 25 | |
| 26 | import datetime |
| 27 | import json |
| 28 | import re |
| 29 | import sys |
| 30 | import time |
| 31 | import urllib.parse |
| 32 | import urllib.request |
| 33 | from typing import Any |
| 34 | |
| 35 | _UA = "Mozilla/5.0 (last30days stocktwits source)" |
| 36 | _STREAM_URL = "https://api.stocktwits.com/api/2/streams/symbol/{symbol}.json" |
| 37 | _SEARCH_URL = "https://api.stocktwits.com/api/2/search/symbols.json" |
| 38 | |
| 39 | # Topic must look financial before we even try to resolve a symbol. This is the |
| 40 | # coarse gate; symbol resolution is the fine gate. |
| 41 | _FINANCE_HINTS = re.compile( |
| 42 | # Unambiguous finance vocabulary only. Bare "share/token/coin/bull/bear" |
| 43 | # were removed: they misfire on general topics ("share files", "token |
| 44 | # limits", "coin collecting", "bear attacks") and would inject stock chatter |
| 45 | # into non-financial runs. |
| 46 | r"\b(stock|stocks|ticker|cashtag|equit(?:y|ies)|price target|" |
| 47 | r"earnings|premarket|pre-?market|after\s?hours|dividend|valuation|" |
| 48 | r"crypto|altcoin|defi|market cap|bullish|bearish|" |
| 49 | # Unambiguous crypto names so "bitcoin price" gates without a cashtag. |
| 50 | # Short aliases (eth, sol, ada, doge, ripple) stay OUT of the gate: they |
| 51 | # collide with everyday topics (ETH Zurich, ADA compliance, doge memes); |
| 52 | # they still resolve via _CRYPTO_ALIASES once the gate fires another way. |
| 53 | r"bitcoin|btc|ethereum|solana|dogecoin|cardano|xrp|" |
| 54 | r"\$[A-Za-z]{1,5}(?:\.[A-Z])?)\b", |
| 55 | re.IGNORECASE, |
| 56 | ) |
| 57 | _CASHTAG = re.compile(r"\$([A-Za-z]{1,5}(?:\.[A-Za-z])?)\b") |
| 58 | _EXPLICIT_TICKER = re.compile(r"[A-Z]{1,5}(?:\.[A-Z])?") |
| 59 | |
| 60 | # A small built-in crypto map so we don't burn a symbol-search call on the |
| 61 | # obvious ones. StockTwits uses the `.X` suffix for crypto symbols. |
| 62 | _CRYPTO_ALIASES = { |
| 63 | "bitcoin": "BTC.X", "btc": "BTC.X", |
| 64 | "ethereum": "ETH.X", "eth": "ETH.X", |
| 65 | "solana": "SOL.X", "sol": "SOL.X", |
| 66 | "dogecoin": "DOGE.X", "doge": "DOGE.X", |
| 67 | "ripple": "XRP.X", "xrp": "XRP.X", |
| 68 | "cardano": "ADA.X", "ada": "ADA.X", |
| 69 | } |
| 70 | |
| 71 | |
| 72 | # Generic finance words that may appear inside real company names (e.g. "Equity |
| 73 | # Residential", "The Trade Desk") so they are NOT stripped from multi-word |
| 74 | # queries, but a topic made up solely of these terms names no company/asset and |
| 75 | # must not trigger a blind StockTwits symbol search. |
| 76 | _GENERIC_FINANCE_WORDS = frozenset({ |
| 77 | "token", "tokens", "coin", "coins", |
| 78 | "dividend", "dividends", "valuation", "valuations", |
| 79 | "market", "markets", "cap", |
| 80 | "equity", "equities", |
| 81 | "premarket", "pre-market", "after", "hours", "afterhours", |
| 82 | "trading", "trade", "trades", |
| 83 | "option", "options", |
| 84 | "bond", "bonds", |
| 85 | "fund", "funds", |
| 86 | "index", "indexes", "indices", |
| 87 | "forex", "futures", |
| 88 | "altcoins", "stocks", "stock", "share", "shares", |
| 89 | "price", "target", "ticker", "tickers", "cashtag", "cashtags", |
| 90 | "earnings", "forecast", "sentiment", "crypto", "defi", |
| 91 | "bullish", "bearish", "etf", "etfs", "watchlist", |
| 92 | }) |
| 93 | |
| 94 | |
| 95 | def _log(msg: str) -> None: |
| 96 | try: |
| 97 | from . import log as _enginelog |
| 98 | _enginelog.source_log("StockTwits", msg, tty_only=False) |
| 99 | except Exception: # standalone / outside package |
| 100 | print(f"[StockTwits] {msg}", file=sys.stderr) |
| 101 | |
| 102 | |
| 103 | def _get_json(url: str, timeout: int = 20) -> dict[str, Any]: |
| 104 | req = urllib.request.Request(url, headers={"User-Agent": _UA}) |
| 105 | with urllib.request.urlopen(req, timeout=timeout) as resp: |
| 106 | return json.load(resp) |
| 107 | |
| 108 | |
| 109 | # --------------------------------------------------------------------------- # |
| 110 | # Gating + symbol resolution # |
| 111 | # --------------------------------------------------------------------------- # |
| 112 | |
| 113 | def is_financial_topic(topic: str) -> bool: |
| 114 | """Coarse gate: does the topic look like it's about a tradeable asset?""" |
| 115 | return bool(_CASHTAG.search(topic) or _FINANCE_HINTS.search(topic)) |
| 116 | |
| 117 | |
| 118 | def detect_symbols(topic: str, *, resolve: bool = True, max_symbols: int = 2) -> list[str]: |
| 119 | """Resolve a topic to StockTwits symbols. Returns [] for non-financial topics. |
| 120 | |
| 121 | Order of resolution: |
| 122 | 1. Explicit cashtags in the topic ($NOW, $BTC.X) — trusted as-is. |
| 123 | 2. Crypto name aliases (bitcoin -> BTC.X), gated behind `is_financial_topic` |
| 124 | so ambiguous short aliases (eth, sol, ada, doge, ripple) never fire on |
| 125 | non-financial topics like "ADA compliance" or "ETH Zurich". |
| 126 | 3. StockTwits symbol-search API for a company/product name, but ONLY if the |
| 127 | topic also tripped the finance gate (so "Apple pie" never resolves AAPL). |
| 128 | |
| 129 | `resolve=False` skips the network call (useful for the cheap gate check). |
| 130 | """ |
| 131 | found: list[str] = [] |
| 132 | |
| 133 | for m in _CASHTAG.finditer(topic): |
| 134 | sym = m.group(1).upper() |
| 135 | if sym not in found: |
| 136 | found.append(sym) |
| 137 | |
| 138 | financial = is_financial_topic(topic) |
| 139 | if financial: |
| 140 | lowered = topic.lower() |
| 141 | for alias, sym in _CRYPTO_ALIASES.items(): |
| 142 | if re.search(rf"(?<!\$)\b{re.escape(alias)}\b", lowered) and sym not in found: |
| 143 | found.append(sym) |
| 144 | |
| 145 | if found: |
| 146 | return found[:max_symbols] |
| 147 | |
| 148 | # No explicit symbol. Only hit the network if the topic looks financial. |
| 149 | if not resolve or not financial: |
| 150 | return [] |
| 151 | |
| 152 | # Strip only clear non-name finance modifiers so company names like |
| 153 | # "Equity Residential" or "Capital One" stay intact for symbol lookup. |
| 154 | name = " ".join( |
| 155 | re.sub( |
| 156 | r"\b(stock|stocks|shares?|price(?:\s+target)?|tickers?|cashtags?|" |
| 157 | r"earnings|forecast|sentiment|crypto|altcoin|defi|" |
| 158 | r"bullish|bearish|etfs?|watchlist|news|today|now)\b", |
| 159 | "", topic, flags=re.IGNORECASE, |
| 160 | ).split() |
| 161 | ) |
| 162 | if not name: |
| 163 | return [] |
| 164 | raw_words = [ |
| 165 | word for word in (tok.strip(".,!?;:\"'()[]{}") for tok in name.split()) if word |
| 166 | ] |
| 167 | mixed_case_topic = not topic.isupper() |
| 168 | |
| 169 | def _is_generic_finance_word(raw_word: str) -> bool: |
| 170 | lowered = raw_word.lower() |
| 171 | # Preserve an uppercase ticker in a mixed-case financial query (e.g. |
| 172 | # "COIN stock", "COIN earnings") while still blocking generic phrases |
| 173 | # like "crypto coin" or all-caps "CRYPTO COIN". |
| 174 | if ( |
| 175 | mixed_case_topic |
| 176 | and _EXPLICIT_TICKER.fullmatch(raw_word) |
| 177 | and lowered not in _CRYPTO_ALIASES |
| 178 | and not _FINANCE_HINTS.fullmatch(raw_word) |
| 179 | ): |
| 180 | return False |
| 181 | return lowered in _GENERIC_FINANCE_WORDS or bool(_FINANCE_HINTS.fullmatch(lowered)) |
| 182 | |
| 183 | if not raw_words or all(_is_generic_finance_word(word) for word in raw_words): |
| 184 | return [] |
| 185 | try: |
| 186 | url = _SEARCH_URL + "?" + urllib.parse.urlencode({"q": name}) |
| 187 | data = _get_json(url) |
| 188 | for result in data.get("results", []): |
| 189 | sym = (result.get("symbol") or "").upper() |
| 190 | if sym and sym not in found: |
| 191 | found.append(sym) |
| 192 | if len(found) >= max_symbols: |
| 193 | break |
| 194 | if found: |
| 195 | _log(f"Resolved '{name}' -> {found}") |
| 196 | except Exception as e: # noqa: BLE001 — network/parse, degrade gracefully |
| 197 | _log(f"symbol search failed for '{name}': {e}") |
| 198 | return found[:max_symbols] |
| 199 | |
| 200 | |
| 201 | # --------------------------------------------------------------------------- # |
| 202 | # Fetch + parse # |
| 203 | # --------------------------------------------------------------------------- # |
| 204 | |
| 205 | _DEPTH = {"quick": 30, "default": 60, "deep": 120} |
| 206 | |
| 207 | |
| 208 | def _is_explicit_symbol(value: str) -> bool: |
| 209 | """Whether `value` is an explicit cashtag ($AAPL, $btc.x) or an unambiguous |
| 210 | all-uppercase ticker (AAPL, BRK.B, BTC.X), not a lowercase word, crypto |
| 211 | alias (BTC, XRP, ETH), or generic finance keyword (DEFI, STOCK).""" |
| 212 | if value.startswith("$"): |
| 213 | return bool(_CASHTAG.fullmatch(value)) |
| 214 | if not _EXPLICIT_TICKER.fullmatch(value): |
| 215 | return False |
| 216 | return value.lower() not in _CRYPTO_ALIASES and not _FINANCE_HINTS.fullmatch(value) |
| 217 | |
| 218 | |
| 219 | def search_stocktwits( |
| 220 | topic_or_symbol: str, |
| 221 | from_date: str | None = None, |
| 222 | to_date: str | None = None, |
| 223 | *, |
| 224 | depth: str = "default", |
| 225 | ) -> dict[str, Any]: |
| 226 | """Fetch the symbol stream for the topic. Paginates by cursor up to `depth`. |
| 227 | |
| 228 | Accepts either a raw topic (resolved via detect_symbols) or an explicit |
| 229 | symbol. Returns {"messages": [...], "symbols": [...], "watchlist": int}. |
| 230 | """ |
| 231 | cleaned = topic_or_symbol.strip() |
| 232 | symbols = ( |
| 233 | [cleaned.lstrip("$").upper()] |
| 234 | if _is_explicit_symbol(cleaned) |
| 235 | else detect_symbols(topic_or_symbol) |
| 236 | ) |
| 237 | if not symbols: |
| 238 | return {"messages": [], "symbols": [], "error": "no symbol resolved"} |
| 239 | |
| 240 | symbol = symbols[0] # primary symbol drives the stream |
| 241 | target = _DEPTH.get(depth, 60) |
| 242 | messages: list[dict[str, Any]] = [] |
| 243 | watchlist = None |
| 244 | cursor_max = None |
| 245 | try: |
| 246 | while len(messages) < target: |
| 247 | url = _STREAM_URL.format(symbol=urllib.parse.quote(symbol)) |
| 248 | if cursor_max: |
| 249 | url += f"?max={cursor_max}" |
| 250 | data = _get_json(url) |
| 251 | if watchlist is None: |
| 252 | watchlist = (data.get("symbol") or {}).get("watchlist_count") |
| 253 | batch = data.get("messages", []) |
| 254 | if not batch: |
| 255 | break |
| 256 | messages.extend(batch) |
| 257 | cursor = data.get("cursor", {}) |
| 258 | if not cursor.get("more") or not cursor.get("max"): |
| 259 | break |
| 260 | cursor_max = cursor["max"] |
| 261 | time.sleep(0.8) # be polite to the unauth quota |
| 262 | except Exception as e: # noqa: BLE001 |
| 263 | _log(f"stream fetch failed for {symbol}: {e}") |
| 264 | messages = _filter_by_date(messages, from_date, to_date) |
| 265 | return { |
| 266 | "messages": messages, |
| 267 | "symbols": symbols, |
| 268 | "error": str(e), |
| 269 | "freshness_window": { |
| 270 | "depth": depth, |
| 271 | "from_date": from_date, |
| 272 | "to_date": to_date, |
| 273 | }, |
| 274 | } |
| 275 | |
| 276 | messages = _filter_by_date(messages, from_date, to_date) |
| 277 | _log(f"{symbol}: {len(messages)} messages (watchlist {watchlist})") |
| 278 | return { |
| 279 | "messages": messages, |
| 280 | "symbols": symbols, |
| 281 | "watchlist": watchlist, |
| 282 | "freshness_window": { |
| 283 | "depth": depth, |
| 284 | "from_date": from_date, |
| 285 | "to_date": to_date, |
| 286 | }, |
| 287 | } |
| 288 | |
| 289 | |
| 290 | def _filter_by_date(messages: list[dict], from_date: str | None, to_date: str | None) -> list[dict]: |
| 291 | if not (from_date or to_date): |
| 292 | return messages |
| 293 | out = [] |
| 294 | for m in messages: |
| 295 | d = (m.get("created_at") or "")[:10] |
| 296 | if from_date and d and d < from_date: |
| 297 | continue |
| 298 | if to_date and d and d > to_date: |
| 299 | continue |
| 300 | out.append(m) |
| 301 | return out |
| 302 | |
| 303 | |
| 304 | def parse_stocktwits_response(response: dict[str, Any], query: str = "") -> list[dict[str, Any]]: |
| 305 | """Normalize the stream into engine-style item dicts (same keys as HN/Reddit). |
| 306 | |
| 307 | Each item carries metadata.sentiment in {"Bullish","Bearish",None} and the |
| 308 | symbol-level bull/bear aggregate so synthesis can cite the ratio. |
| 309 | """ |
| 310 | messages = response.get("messages", []) |
| 311 | symbols = response.get("symbols", []) |
| 312 | agg = aggregate_sentiment(messages) |
| 313 | items: list[dict[str, Any]] = [] |
| 314 | for i, m in enumerate(messages): |
| 315 | user = m.get("user") or {} |
| 316 | username = user.get("username") or "unknown" |
| 317 | body = (m.get("body") or "").strip() |
| 318 | sentiment = ((m.get("entities") or {}).get("sentiment") or {}).get("basic") |
| 319 | likes = (m.get("likes") or {}).get("total", 0) or 0 |
| 320 | reshares = (m.get("reshares") or {}).get("reshared_count", 0) or 0 |
| 321 | followers = user.get("followers", 0) or 0 |
| 322 | # Relevance: cashtag-native source, so on-symbol is a near-given. Nudge |
| 323 | # by author reach + a tagged-sentiment bonus (tagged posts are higher |
| 324 | # intent than chatter). |
| 325 | relevance = min(1.0, 0.7 + (0.1 if sentiment else 0.0) + min(0.2, followers / 50000)) |
| 326 | items.append({ |
| 327 | "id": str(m.get("id") or f"ST{i+1}"), |
| 328 | "title": body[:120] or f"${symbols[0] if symbols else ''} post", |
| 329 | "url": f"https://stocktwits.com/{username}/message/{m.get('id')}", |
| 330 | "author": username, |
| 331 | "date": (m.get("created_at") or "")[:10] or None, |
| 332 | "engagement": {"likes": likes, "reshares": reshares, "followers": followers}, |
| 333 | "relevance": round(relevance, 2), |
| 334 | "why_relevant": f"StockTwits ${symbols[0] if symbols else ''} post" |
| 335 | + (f" tagged {sentiment}" if sentiment else ""), |
| 336 | "snippet": body[:400], |
| 337 | "metadata": { |
| 338 | "sentiment": sentiment, |
| 339 | "symbol": symbols[0] if symbols else None, |
| 340 | "sentiment_aggregate": agg, # same dict on every item; cheap, lets synthesis cite it |
| 341 | "watchlist": response.get("watchlist"), |
| 342 | "freshness_window": response.get("freshness_window"), |
| 343 | }, |
| 344 | }) |
| 345 | return items |
| 346 | |
| 347 | |
| 348 | def aggregate_sentiment(messages: list[dict[str, Any]]) -> dict[str, Any]: |
| 349 | """Bull/bear counts + ratio over the sentiment-tagged subset.""" |
| 350 | bull = bear = 0 |
| 351 | for m in messages: |
| 352 | s = ((m.get("entities") or {}).get("sentiment") or {}).get("basic") |
| 353 | if s == "Bullish": |
| 354 | bull += 1 |
| 355 | elif s == "Bearish": |
| 356 | bear += 1 |
| 357 | tagged = bull + bear |
| 358 | return { |
| 359 | "bullish": bull, |
| 360 | "bearish": bear, |
| 361 | "untagged": len(messages) - tagged, |
| 362 | "pct_bullish": round(100 * bull / tagged) if tagged else None, |
| 363 | "sample": len(messages), |
| 364 | } |
| 365 | |
| 366 | |
| 367 | def refetch_datum(item: Any, datum_key: str) -> dict[str, Any]: |
| 368 | """Re-fetch the same paginated, date-filtered symbol-stream population.""" |
| 369 | from . import http |
| 370 | |
| 371 | if datum_key != "pct_bullish": |
| 372 | raise KeyError(f"Unsupported StockTwits datum: {datum_key}") |
| 373 | symbol = str(item.metadata.get("symbol") or item.container or "").strip().upper() |
| 374 | if not symbol: |
| 375 | raise ValueError("StockTwits item has no symbol") |
| 376 | url = _STREAM_URL.format(symbol=urllib.parse.quote(symbol)) |
| 377 | window = item.metadata.get("freshness_window") or {} |
| 378 | depth = str(window.get("depth") or "default") |
| 379 | target = _DEPTH.get(depth, _DEPTH["default"]) |
| 380 | messages: list[dict[str, Any]] = [] |
| 381 | cursor_max = None |
| 382 | while len(messages) < target: |
| 383 | request_kwargs: dict[str, Any] = {"timeout": 10, "retries": 2} |
| 384 | if cursor_max: |
| 385 | request_kwargs["params"] = {"max": cursor_max} |
| 386 | data = http.request("GET", url, **request_kwargs) |
| 387 | if not isinstance(data, dict) or not isinstance(data.get("messages"), list): |
| 388 | raise KeyError("StockTwits symbol stream was not returned") |
| 389 | batch = data["messages"] |
| 390 | if not batch: |
| 391 | break |
| 392 | messages.extend(batch) |
| 393 | cursor = data.get("cursor") or {} |
| 394 | if not cursor.get("more") or not cursor.get("max"): |
| 395 | break |
| 396 | cursor_max = cursor["max"] |
| 397 | messages = _filter_by_date( |
| 398 | messages, |
| 399 | window.get("from_date"), |
| 400 | window.get("to_date"), |
| 401 | ) |
| 402 | aggregate = aggregate_sentiment(messages) |
| 403 | value = aggregate.get("pct_bullish") |
| 404 | if value is None: |
| 405 | raise KeyError("StockTwits stream has no tagged sentiment") |
| 406 | newest = max( |
| 407 | (str(message.get("created_at") or "") for message in messages), |
| 408 | default="", |
| 409 | ) |
| 410 | return { |
| 411 | "value": value, |
| 412 | "values": {"pct_bullish": value}, |
| 413 | "url": item.url, |
| 414 | "timestamp": newest or None, |
| 415 | } |
| 416 | |
| 417 | |
| 418 | # --------------------------------------------------------------------------- # |
| 419 | # Standalone CLI (ad-hoc use today, before any engine wiring) # |
| 420 | # python3 stocktwits.py "ServiceNow stock" # |
| 421 | # --------------------------------------------------------------------------- # |
| 422 | if __name__ == "__main__": |
| 423 | topic = " ".join(sys.argv[1:]) or "$NOW" |
| 424 | if not is_financial_topic(topic) and not detect_symbols(topic, resolve=False): |
| 425 | print(f"Not a ticker/crypto topic — skipping StockTwits: {topic!r}") |
| 426 | raise SystemExit(0) |
| 427 | today = datetime.date.today() |
| 428 | since = (today - datetime.timedelta(days=30)).isoformat() |
| 429 | resp = search_stocktwits(topic, from_date=since, depth="default") |
| 430 | if resp.get("error") and not resp.get("messages"): |
| 431 | print("error:", resp["error"]); raise SystemExit(1) |
| 432 | items = parse_stocktwits_response(resp, query=topic) |
| 433 | agg = aggregate_sentiment(resp["messages"]) |
| 434 | print(f"symbol(s): {resp.get('symbols')} | watchlist {resp.get('watchlist')}") |
| 435 | print(f"sentiment: {agg['bullish']} bull / {agg['bearish']} bear " |
| 436 | f"({agg['pct_bullish']}% bullish of tagged) over {agg['sample']} msgs") |
| 437 | for it in sorted(items, key=lambda x: x["engagement"]["likes"], reverse=True)[:8]: |
| 438 | s = it["metadata"]["sentiment"] or "-" |
| 439 | print(f" [{it['engagement']['likes']}♥ {s}] @{it['author']}: {it['snippet'][:120]}") |
| 440 |