diff --git a/.github/workflows/research.yml b/.github/workflows/research.yml index 58e01abfd..e0c5d7083 100644 --- a/.github/workflows/research.yml +++ b/.github/workflows/research.yml @@ -13,7 +13,7 @@ on: workflow_dispatch: inputs: tasks: - description: "Comma list: quality,spreads,edge,alt,poisson,conditional,combos,garch,glm,strategies,events,survivorship,hmm,consumer,news,asia,flip,multi (blank = all)" + description: "Comma list: quality,spreads,edge,alt,poisson,conditional,combos,garch,glm,strategies,events,survivorship,hmm,consumer,news,sentiment,asia,flip,multi (blank = all)" default: "" permissions: @@ -108,7 +108,7 @@ jobs: # a partial run (some tasks only) adds its files to latest instead of replacing it mkdir -p research/latest && cp -r "$GITHUB_WORKSPACE/reports/research/." research/latest/ { echo "# Research results"; echo - for f in data_quality spreads edge alt poisson conditional combos garch glm strategies multi flip consumer events survivorship intraday hmm; do + for f in data_quality spreads edge alt poisson conditional combos garch glm strategies multi flip consumer sentiment events survivorship intraday hmm; do [ -f "research/latest/$f.md" ] && { cat "research/latest/$f.md"; echo; } done; } > research/latest/README.md git add -A && git commit -q -m "Research run ${GITHUB_SHA::7} (run ${{ github.run_id }})" diff --git a/.github/workflows/sentiment-sheet.yml b/.github/workflows/sentiment-sheet.yml new file mode 100644 index 000000000..4d1c71af9 --- /dev/null +++ b/.github/workflows/sentiment-sheet.yml @@ -0,0 +1,44 @@ +name: sentiment-sheet + +# The $0 news sentiment tracker (qtrade/intraday/sentiment_sheet.py) - NOT part of the $10,000 book. Every +# weekday after the close: the morning's news (out by 9:25 New York) is scored, split by each stock's past +# day / month, and the news_sentiment study's rules are booked open -> close at the official auction prices +# in the sheet's "Sentiment tracker" tab. Nothing is sent to a broker. + +on: + schedule: + - cron: "47 22,23 * * 1-5" # backup for the clock's 17:35 New York run; a booked day is skipped + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: sentiment-sheet + cancel-in-progress: false + +jobs: + tracker: + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + ALPACA_API_KEY: ${{ secrets.ALPACA_API_KEY }} # market data and news only + ALPACA_SECRET_KEY: ${{ secrets.ALPACA_SECRET_KEY }} + GOOGLE_SERVICE_ACCOUNT_JSON: ${{ secrets.GOOGLE_SERVICE_ACCOUNT_JSON }} + HFT_SHEET_ID: ${{ secrets.HFT_SHEET_ID }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + - run: pip install -r requirements.txt + - name: Universe and the study's rules + run: | + git fetch -q --depth 1 origin results + mkdir -p data + git show origin/results:intraday/latest/model.json > data/auction_tickers.json + git show origin/results:research/latest/sentiment_rules.json > data/sentiment_rules.json || { echo "no study yet"; rm -f data/sentiment_rules.json; } + - name: Tracker + if: hashFiles('data/sentiment_rules.json') != '' + run: python -m qtrade.intraday.sentiment_sheet diff --git a/qtrade/clock.py b/qtrade/clock.py index fd614344d..09bafd37b 100644 --- a/qtrade/clock.py +++ b/qtrade/clock.py @@ -42,6 +42,7 @@ class Job: Job("hoard-archive.yml", NY, ("16:45",), inputs=(("job", "eod"),), window_min=400), Job("foreign-sheet.yml", "UTC", ("17:15", "23:30"), window_min=200), # 23:30: Asian bars Yahoo posted late Job("crm-sheet.yml", NY, ("17:20",), window_min=300), # $0 CRM satellite tracker (marks at the close) + Job("sentiment-sheet.yml", NY, ("17:35",), window_min=300), # $0 news sentiment tracker (open -> close) Job("hoard-archive.yml", "UTC", ("07:15",), weekdays=False, inputs=(("job", "archive"),), window_min=300), ] diff --git a/qtrade/intraday/sentiment_sheet.py b/qtrade/intraday/sentiment_sheet.py new file mode 100644 index 000000000..959564dea --- /dev/null +++ b/qtrade/intraday/sentiment_sheet.py @@ -0,0 +1,214 @@ +"""News sentiment tracker: the ``news_sentiment`` study's rules, run live in the sheet with $0 +allocated - not part of the $10,000 book. + +Every weekday after the close (``python -m qtrade.intraday.sentiment_sheet``): + +1. every article Alpaca's news feed (Benzinga) published between the previous trading day's 9:25 and + today's 9:25 New York for the universe is scored exactly as in the study (word-list tone of the + headline and summary plus signed headline events; roundups tagging more than 3 stocks dropped); +2. each stock's past performance - yesterday's move and the past month's, relative to the average + stock - is split into terciles across the universe; +3. each study rule (sentiment x past tercile -> long or short, open to close) picks its names, and + the legs are bought / sold at today's official open and closed at the official close, on a + hypothetical $10,000 split equally between the legs. As in the study, returns are measured + against the average stock (the book is hedged with the equal-weight universe). + +Rules: the open-to-close rules in ``sentiment_rules.json`` (research/latest on the results branch) +that kept their sign on the study's test years; if none did, every rule that passed training, and +the status line says so. The daily log is in the "Sentiment tracker" tab, today's legs beside it. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path + +import numpy as np +import pandas as pd + +from ..research import news_sentiment as N +from ..utils import LOG + +NY = "America/New_York" +TAB = "Sentiment tracker" +BOOK_USD = 10_000.0 +MARK_AFTER_MIN = 16 * 60 + 30 +LOG_HEADER = ["Date", "Stocks with news", "Legs", "Long", "Short", "Day P&L $", "Day %", "Equity $", "Note"] +LEG_HEADER = ["Symbol", "Rule", "Side", "Articles", "Score", "Past 1d %", "Past 21d %", "Position $", "Open", + "Close", "Return vs avg %", "P&L $"] + + +# --- pure pieces --------------------------------------------------------------------------------- +def pick_rules(spec: dict) -> tuple[list[dict], str]: + rules = [r for r in spec.get("rules", []) if r["target"] == "intraday"] + live = [r for r in rules if r.get("t_test") is not None and np.sign(r["t_test"]) == r["direction"]] + if live: + return live, f"{len(live)} open-to-close rules that held up on the study's test years" + return rules, (f"{len(rules)} open-to-close rules from the training years (none held up on the test years - " + "tracked to see if they come back)") + + +def day_sentiment(scores: pd.DataFrame, since: pd.Timestamp, until: pd.Timestamp) -> pd.DataFrame: + """Per ticker: mean score and article count of the articles in [since, until).""" + t = pd.to_datetime(scores["created_at"], utc=True) + x = scores[(t >= since) & (t < until)] + return x.groupby("ticker")["score"].agg(["mean", "size"]).rename(columns={"mean": "score", "size": "articles"}) + + +def past_terciles(close: pd.DataFrame, day: pd.Timestamp) -> pd.DataFrame: + """Per ticker: relative past moves (to the close before ``day``) and their terciles across the universe.""" + hist = close[close.index < day] + out = {} + for name, n in N.PASTS.items(): + if len(hist) <= n: + continue + r = (hist.iloc[-1] / hist.iloc[-1 - n] - 1).clip(-0.5, 0.5) + r = r - r.mean() + out[name] = r + out[f"{name}_t"] = np.floor(r.rank(pct=True).clip(upper=0.999999) * 3) + return pd.DataFrame(out) + + +def legs(rules: list[dict], sent: pd.DataFrame, past: pd.DataFrame) -> pd.DataFrame: + rows = [] + df = sent.join(past, how="inner") + for r in rules: + smask = df["score"] > 0 if r["sentiment"] == "positive" else df["score"] < 0 + m = smask & (df[f"{r['past']}_t"] == N.TERCILES.index(r["past_tercile"])) + for t, row in df[m].iterrows(): + rows.append({"Symbol": t, "Rule": f"{r['sentiment']} news, {r['past']} {r['past_tercile']}", + "dir": r["direction"], "Articles": int(row["articles"]), "Score": round(row["score"], 2), + "Past 1d %": round(100 * row.get("past_1d", np.nan), 2), + "Past 21d %": round(100 * row.get("past_21d", np.nan), 2)}) + return pd.DataFrame(rows) + + +def settle(lg: pd.DataFrame, open_: pd.Series, close: pd.Series, equity: float) -> tuple[pd.DataFrame, float]: + """Each leg gets equity / legs; P&L on the open-to-close move minus the average stock's.""" + ok = open_.notna() & close.notna() & (open_ > 0) + avg = float((close[ok] / open_[ok] - 1).clip(-0.5, 0.5).mean()) if ok.any() else 0.0 + lg = lg[lg["Symbol"].map(ok).fillna(False).astype(bool)].copy() if len(lg) else lg + if lg.empty: + return pd.DataFrame(columns=LEG_HEADER), 0.0 + size = equity / len(lg) + lg["Side"] = np.where(lg["dir"] > 0, "long", "short") + lg["Position $"] = round(size, 2) + lg["Open"] = lg["Symbol"].map(open_).round(4) + lg["Close"] = lg["Symbol"].map(close).round(4) + rel = (lg["Close"] / lg["Open"] - 1).clip(-0.5, 0.5) - avg + lg["Return vs avg %"] = (100 * rel).round(3) + lg["P&L $"] = (lg["dir"] * size * rel).round(2) + return lg[LEG_HEADER], float(lg["P&L $"].sum()) + + +# --- data and sheet ------------------------------------------------------------------------------ +def fetch(tickers: list[str], day: pd.Timestamp) -> dict: + from ..data.intraday import AlpacaBars + from ..data.news import articles_to_frame, fetch_window + from .auction_live import _fetch + + data = AlpacaBars(feed="sip") + start = day.tz_localize(NY) + daily = _fetch(data, tickers, "1Day", start - pd.Timedelta(days=50), pd.Timestamp.now(tz=NY) - pd.Timedelta(minutes=16), + "sip") + frames = {} + for f in ("open", "close"): + frames[f] = pd.DataFrame({t: d[f].set_axis(d.index.tz_convert(NY).tz_localize(None).normalize()) + for t, d in daily.items() if len(d)}) + close = frames["close"].sort_index() + prev_days = close.index[close.index < day] + prev = prev_days[-1] if len(prev_days) else day - pd.Timedelta(days=1) + since = (prev + pd.Timedelta(hours=9, minutes=25)).tz_localize(NY).tz_convert("UTC") + until = (day + pd.Timedelta(hours=9, minutes=25)).tz_localize(NY).tz_convert("UTC") + news = articles_to_frame(fetch_window(data, tickers, since.isoformat(), until.isoformat())) + return {"open": frames["open"], "close": close, "news": news, "since": since, "until": until} + + +class Sheet: + def __init__(self, sheet_id: str, creds_json: str): + from google.auth.transport.requests import AuthorizedSession + from google.oauth2 import service_account + + creds = service_account.Credentials.from_service_account_info( + json.loads(creds_json), scopes=["https://www.googleapis.com/auth/spreadsheets"]) + self.s = AuthorizedSession(creds) + self.base = f"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}" + meta = self.s.get(self.base, params={"fields": "sheets.properties.title"}, timeout=30).json() + if TAB not in [x["properties"]["title"] for x in meta.get("sheets", [])]: + self.s.post(f"{self.base}:batchUpdate", json={"requests": [{"addSheet": {"properties": {"title": TAB}}}]}, + timeout=30).raise_for_status() + + def log(self) -> list[list]: + r = self.s.get(f"{self.base}/values/'{TAB}'!A6:I100000", params={"valueRenderOption": "UNFORMATTED_VALUE"}, + timeout=60) + r.raise_for_status() + return [x for x in r.json().get("values", []) if x and x[0]] + + def write(self, status: str, row: list, n_log: int, lg: pd.DataFrame) -> None: + title = ("News sentiment tracker - $0 allocated, NOT part of the $10,000 book. Each weekday, stocks with news " + "out by 9:25 New York are scored (headline tone + events) and split by their past day's / month's " + "move; the news_sentiment study's rules go long / short at the official open and close at the " + "official close, hedged against the average stock, on a hypothetical $10,000.") + self.s.post(f"{self.base}/values:batchClear", json={"ranges": [f"'{TAB}'!K6:V2000"]}, + timeout=30).raise_for_status() + data = [{"range": f"'{TAB}'!A1", "values": [[title]]}, {"range": f"'{TAB}'!A3", "values": [[status]]}, + {"range": f"'{TAB}'!A5:I5", "values": [LOG_HEADER]}, + {"range": f"'{TAB}'!A{6 + n_log}:I{6 + n_log}", "values": [row]}, + {"range": f"'{TAB}'!K5:V5", "values": [LEG_HEADER]}] + if len(lg): + data.append({"range": f"'{TAB}'!K6:V{5 + len(lg)}", + "values": lg.astype(object).where(lg.notna(), "").values.tolist()}) + self.s.post(f"{self.base}/values:batchUpdate", json={"valueInputOption": "RAW", "data": data}, + timeout=30).raise_for_status() + + +def run(spec: dict, tickers: list[str], dry_run: bool = False) -> dict: + now = pd.Timestamp.now(tz=NY) + day = now.tz_localize(None).normalize() + if now.weekday() >= 5 or now.hour * 60 + now.minute < MARK_AFTER_MIN: + return {"skipped": f"{now:%a %H:%M} New York - runs on weekdays after 16:30"} + sheet = None if dry_run else Sheet(os.environ["HFT_SHEET_ID"], os.environ["GOOGLE_SERVICE_ACCOUNT_JSON"]) + log = sheet.log() if sheet else [] + if log and str(log[-1][0])[:10] == f"{day:%Y-%m-%d}": + return {"skipped": "already booked today"} + d = fetch(tickers, day) + if day not in d["close"].index or d["close"].loc[day].notna().sum() < 0.5 * len(tickers): + return {"skipped": f"no official closes for {day:%Y-%m-%d} (market closed or data late)"} + rules, which = pick_rules(spec) + scores = N.article_scores(d["news"]) if len(d["news"]) else pd.DataFrame(columns=["created_at", "ticker", "score"]) + sent = day_sentiment(scores[scores["ticker"].isin(set(tickers))], d["since"], d["until"]) + past = past_terciles(d["close"], day) + equity0 = float(log[-1][7]) if log else BOOK_USD + lg, pnl = settle(legs(rules, sent, past), d["open"].loc[day] if day in d["open"].index else pd.Series(dtype=float), + d["close"].loc[day], equity0) + equity = equity0 + pnl + n_long, n_short = int((lg["Side"] == "long").sum()) if len(lg) else 0, int((lg["Side"] == "short").sum()) if len(lg) else 0 + row = [f"{day:%Y-%m-%d}", int(len(sent)), int(len(lg)), n_long, n_short, round(pnl, 2), + round(100 * pnl / equity0, 4) if equity0 else 0.0, round(equity, 2), "" if len(lg) else "no stock matched a rule"] + status = (f"Updated {now:%Y-%m-%d %H:%M} New York - today ${pnl:+,.2f} on {len(lg)} legs ({n_long} long / {n_short} " + f"short, {len(sent)} stocks with news); equity ${equity:,.2f} (${equity - BOOK_USD:+,.2f} since the start). " + f"Trading {which}.") + if sheet: + sheet.write(status, row, len(log), lg.sort_values("P&L $") if len(lg) else lg) + LOG.info("sentiment tracker: %s", status) + return {"day": row[0], "legs": len(lg), "pnl": round(pnl, 2), "equity": round(equity, 2)} + + +def main(argv=None): + import argparse + + from ..utils import setup_logging + from .auction_live import load_inputs + + ap = argparse.ArgumentParser() + ap.add_argument("--rules", default="data/sentiment_rules.json") + ap.add_argument("--tickers", default="data/auction_tickers.json") + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args(argv) + setup_logging() + tickers, _ = load_inputs(args.tickers, None) + print(run(json.loads(Path(args.rules).read_text()), tickers, dry_run=args.dry_run)) + + +if __name__ == "__main__": + main() diff --git a/qtrade/research/__main__.py b/qtrade/research/__main__.py index 95b27da9d..82590f753 100644 --- a/qtrade/research/__main__.py +++ b/qtrade/research/__main__.py @@ -66,6 +66,9 @@ def main(argv=None): elif task == "asia": from .asia import run summary[task] = run(md, ctx, out, cfg) + elif task == "sentiment": + from .news_sentiment import run + summary[task] = run(md, ctx, out, cfg) elif task == "news": from .news_zoo import run summary[task] = run(md, ctx, out, cfg) diff --git a/qtrade/research/news_sentiment.py b/qtrade/research/news_sentiment.py new file mode 100644 index 000000000..40b63e469 --- /dev/null +++ b/qtrade/research/news_sentiment.py @@ -0,0 +1,265 @@ +"""News sentiment vs the stock's past performance (research task "sentiment"). + +Does a stock's news tell us where it goes next, and does that depend on how the stock had been +doing? Every Benzinga article (headline + summary, Alpaca's news feed, 2015 on) tagging at most +three stocks gets a sentiment score: the word-list tone of ``alt_signals`` plus signed headline +events (beats / misses, upgrades / downgrades, guidance, buybacks, lawsuits, ...). Each stock and +trading day d gets the mean score of the articles published since the previous day's 9:25 and +before 9:25 New York on d - what a trader knows before the opening auction - and is traded from +d's official open: + +* targets: open-to-close on d (``intraday``) and open on d to the close five sessions later + (``hold_5d``), relative to the average stock; +* past performance, known at the open: yesterday's move (close d-2 -> d-1) and the past month's + (close d-22 -> d-1), both relative to the average stock, split into terciles across the stocks; +* cells: sentiment (positive / negative) x past tercile (loser / middle / winner), for each of + the two past windows. A cell's daily return is the mean over its names; t-stats are over days. + +Directions are fixed on 2016-2021 (|t| >= 2) and judged on 2022-2026 at 0 bp and after +``COST_BP`` per round trip (official auctions). The cells that pass are written to +``sentiment_rules.json`` for the $0 sentiment tracker (``qtrade.intraday.sentiment_sheet``). +""" +from __future__ import annotations + +import json +import re +from pathlib import Path + +import numpy as np +import pandas as pd + +from ..utils import LOG + +NY = "America/New_York" +TRAIN = ("2016-01-01", "2021-12-31") +TEST = ("2022-01-01", "2026-12-31") +CUTOFF = pd.Timedelta(minutes=5) # news must be out by 9:25 to trade at the 9:30 open +MAX_TAGGED = 3 +COST_BP = 5.0 +MIN_T = 2.0 +EVENT_SIGN = { + "upgrade": 1, "pt_raised": 1, "beat": 1, "guidance_up": 1, "buyback": 1, "dividend_up": 1, "insider_buy": 1, + "record": 1, "new_high": 1, "contract": 1, "partnership": 1, + "downgrade": -1, "pt_cut": -1, "miss": -1, "guidance_down": -1, "lawsuit": -1, "investigation": -1, + "offering": -1, "layoffs": -1, "ceo_change": -1, "short_report": -1, "recall": -1, "bankruptcy": -1, + "new_low": -1, +} +PASTS = {"past_1d": 1, "past_21d": 21} +TERCILES = ["loser", "middle", "winner"] + + +# --- article scores ------------------------------------------------------------------------------ +def _flags(): + from .news_zoo import HEADLINE_FLAGS + + return {k: re.compile(re.sub(r"\((?!\?)", "(?:", HEADLINE_FLAGS[k])) for k in EVENT_SIGN if k in HEADLINE_FLAGS} + + +def score_text(headline: str, summary: str = "", flags=None) -> float: + """Tone of headline + summary (-1..1) plus the signed headline events, clipped to -2..2.""" + from .alt_signals import _tone + + flags = flags if flags is not None else _flags() + h = (headline or "").lower() + ev = sum(EVENT_SIGN[k] for k, rx in flags.items() if rx.search(h)) + return float(np.clip(_tone(f"{headline} {summary}") + ev, -2, 2)) + + +def article_scores(news: pd.DataFrame) -> pd.DataFrame: + """One row per (article, tagged ticker): created_at, ticker, score; roundups (> MAX_TAGGED tags) dropped.""" + flags = _flags() + x = news[["created_at", "headline", "summary", "symbols"]].copy() + x["ticker"] = x["symbols"].fillna("").str.split(",") + x = x[x["ticker"].str.len().between(1, MAX_TAGGED)] + from .alt_signals import _tone + + h = x["headline"].fillna("").astype(str) + ev = sum(EVENT_SIGN[k] * h.str.lower().str.contains(rx, regex=True).astype(int) for k, rx in flags.items()) + tone = (h + " " + x["summary"].fillna("").astype(str)).map(_tone) + x["score"] = (tone + ev).clip(-2, 2) + x = x.explode("ticker") + return x[x["ticker"] != ""][["created_at", "ticker", "score"]].reset_index(drop=True) + + +def entry_positions(created_at: pd.Series, dates: pd.DatetimeIndex) -> np.ndarray: + """Position in ``dates`` of the first session that an article out by 9:25 can be traded at.""" + from .news_zoo import entry_of_times + + return entry_of_times(pd.to_datetime(created_at, utc=True) + CUTOFF, dates) + + +def sentiment_panel(scores: pd.DataFrame, dates: pd.DatetimeIndex, tickers) -> pd.DataFrame: + """Mean article score per (entry session, ticker); NaN where the stock had no news.""" + pos = entry_positions(scores["created_at"], dates) + ok = (pos < len(dates)) & scores["ticker"].isin(set(tickers)).to_numpy() + x = scores[ok].assign(day=dates[pos[ok]]) + m = x.groupby(["day", "ticker"])["score"].mean().unstack() + return m.reindex(index=dates, columns=list(tickers)) + + +# --- past performance and targets ---------------------------------------------------------------- +def _rel(df: pd.DataFrame) -> pd.DataFrame: + df = df.clip(-0.5, 0.5) + return df.sub(df.mean(axis=1), axis=0) + + +def past_moves(close: pd.DataFrame) -> dict[str, pd.DataFrame]: + """Known at day d's open: the move up to d-1's close, relative to the average stock.""" + return {k: _rel(close.shift(1) / close.shift(1 + n) - 1) for k, n in PASTS.items()} + + +def terciles(past: pd.DataFrame, mask: pd.DataFrame) -> pd.DataFrame: + """0 / 1 / 2 = loser / middle / winner across the tradable stocks each day (NaN elsewhere).""" + r = past.where(mask).rank(axis=1, pct=True) + return np.floor(r.clip(upper=0.999999) * 3) + + +def targets(open_: pd.DataFrame, close: pd.DataFrame) -> dict[str, pd.DataFrame]: + return {"intraday": _rel(close / open_ - 1), "hold_5d": _rel(close.shift(-4) / open_ - 1)} + + +# --- cells and the strategy ---------------------------------------------------------------------- +def _t(x: pd.Series, horizon: int) -> float: + x = x.dropna() + if len(x) < 30 or x.std() == 0: + return np.nan + if horizon > 1: # overlapping holds: thin to every horizon-th day + x = x.iloc[::horizon] + return float(x.mean() / x.std(ddof=1) * np.sqrt(len(x))) + + +def _period(s: pd.Series, period) -> pd.Series: + if s.empty: + return s + return s[(s.index >= pd.Timestamp(period[0])) & (s.index <= pd.Timestamp(period[1]))] + + +def cell_daily(sent, terc, target) -> dict[tuple[str, str], pd.Series]: + """(sentiment, past tercile) -> the cell's mean relative return per day.""" + out = {} + for sname, smask in (("positive", sent > 0), ("negative", sent < 0)): + for k, tname in enumerate(TERCILES): + m = smask & (terc == k) + out[(sname, tname)] = target.where(m).mean(axis=1) + return out + + +def scan(sent, pasts_t, tg, horizons) -> pd.DataFrame: + rows = [] + for pname, terc in pasts_t.items(): + n_names = {} + for tname, target in tg.items(): + for (sname, cname), d in cell_daily(sent, terc, target).items(): + key = (sname, cname) + if key not in n_names: + m = ((sent > 0) if sname == "positive" else (sent < 0)) & (terc == TERCILES.index(cname)) + n_names[key] = m.sum(axis=1) + tr, te = _period(d, TRAIN), _period(d, TEST) + h = horizons[tname] + rows.append({"past": pname, "past_tercile": cname, "sentiment": sname, "target": tname, + "names_per_day": round(float(_period(n_names[key], TEST).mean()), 2), + "days_train": int(tr.notna().sum()), "days_test": int(te.notna().sum()), + "bp_train": 1e4 * tr.mean(), "t_train": _t(tr, h), + "bp_test": 1e4 * te.mean(), "t_test": _t(te, h)}) + return pd.DataFrame(rows) + + +def rules_from(cells: pd.DataFrame) -> list[dict]: + """Cells with |t_train| >= MIN_T; direction = the training sign (the test years don't choose).""" + out = [] + for _, r in cells.iterrows(): + if np.isfinite(r["t_train"]) and abs(r["t_train"]) >= MIN_T: + out.append({"past": r["past"], "past_tercile": r["past_tercile"], "sentiment": r["sentiment"], + "target": r["target"], "direction": int(np.sign(r["bp_train"])), + "bp_train": round(float(r["bp_train"]), 2), "t_train": round(float(r["t_train"]), 2), + "bp_test": round(float(r["bp_test"]), 2), + "t_test": None if not np.isfinite(r["t_test"]) else round(float(r["t_test"]), 2)}) + return out + + +def strategy(rules: list[dict], sent, pasts_t, tg, target: str) -> pd.Series: + """Daily return of the book trading every rule for ``target``: equal weight per (name, rule) leg.""" + num, den = None, None + for r in (r for r in rules if r["target"] == target): + smask = (sent > 0) if r["sentiment"] == "positive" else (sent < 0) + m = smask & (pasts_t[r["past"]] == TERCILES.index(r["past_tercile"])) + x = (r["direction"] * tg[target]).where(m) + num = x.fillna(0).sum(axis=1) if num is None else num + x.fillna(0).sum(axis=1) + den = m.sum(axis=1) if den is None else den + m.sum(axis=1) + if num is None: + return pd.Series(dtype=float, index=pd.DatetimeIndex([])) + return (num / den.replace(0, np.nan)).dropna() + + +def perf(d: pd.Series, horizon: int, cost_bp: float = 0.0) -> dict: + d = d - cost_bp / 1e4 / horizon # a 5-day hold pays one round trip per five days + if len(d) < 30: + return {"days": len(d), "bp_day": np.nan, "sharpe": np.nan} + return {"days": len(d), "bp_day": round(1e4 * d.mean(), 2), + "sharpe": round(float(d.mean() / d.std(ddof=1) * np.sqrt(252 / horizon)), 2)} + + +# --- the task ------------------------------------------------------------------------------------ +def run(md, ctx, out: Path, cfg) -> dict: + from ..data.news import load_news + + npath = Path(cfg.data.cache_dir) / "news" + if not any(npath.glob("news_*.parquet")): + LOG.warning("sentiment: no news data") + return {"skipped": "no news data"} + news = load_news(npath) + LOG.info("sentiment: %d articles", len(news)) + dates, tickers = md.dates, list(md.tickers) + sc = article_scores(news) + sent = sentiment_panel(sc, dates, tickers) + mask = ctx.tradable.reindex(index=dates, columns=tickers).fillna(False).astype(bool) + sent = sent.where(mask) + LOG.info("sentiment: %d stock-days with news (%.1f per day)", int(sent.notna().sum().sum()), + float(sent.notna().sum(axis=1).mean())) + pasts_t = {k: terciles(v, mask) for k, v in past_moves(md.close).items()} + tg = targets(md.open, md.close) + horizons = {"intraday": 1, "hold_5d": 5} + cells = scan(sent, pasts_t, tg, horizons) + cells.to_csv(out / "sentiment_cells.csv", index=False) + rules = rules_from(cells) + books = [] + for target, h in horizons.items(): + d = strategy(rules, sent, pasts_t, tg, target) + for label, period in (("train", TRAIN), ("test", TEST)): + x = _period(d, period) + books.append({"target": target, "period": label, "rules": sum(r["target"] == target for r in rules), + **{f"{k}_0bp": v for k, v in perf(x, h).items()}, + **{f"{k}_{COST_BP:g}bp": v for k, v in perf(x, h, COST_BP).items() if k != "days"}}) + # the plain baseline: every stock with news, long positive / short negative, no past split + base = (np.sign(sent) * tg[target]).where(sent != 0).mean(axis=1).dropna() + for label, period in (("train", TRAIN), ("test", TEST)): + books.append({"target": target, "period": f"{label} (sentiment only)", "rules": 0, + **{f"{k}_0bp": v for k, v in perf(_period(base, period), h).items()}, + **{f"{k}_{COST_BP:g}bp": v for k, v in perf(_period(base, period), h, COST_BP).items() + if k != "days"}}) + books = pd.DataFrame(books) + books.to_csv(out / "sentiment_books.csv", index=False) + live = [r for r in rules if r["t_test"] is not None and np.sign(r["t_test"]) == r["direction"]] + (out / "sentiment_rules.json").write_text(json.dumps( + {"made": f"{pd.Timestamp.now(tz='UTC'):%Y-%m-%d}", "train": TRAIN, "test": TEST, "cutoff": "09:25 New York", + "max_tagged": MAX_TAGGED, "rules": rules, "rules_holding_up_in_test": len(live)}, indent=1)) + return report(cells, books, rules, out) + + +def report(cells: pd.DataFrame, books: pd.DataFrame, rules: list[dict], out: Path) -> dict: + show = cells.copy() + for c in ("bp_train", "t_train", "bp_test", "t_test"): + show[c] = show[c].round(2) + lines = ["## News sentiment vs the stock's past performance", "", + "Benzinga articles (headline + summary, at most 3 tagged stocks) scored by word-list tone plus signed " + "headline events; each stock-day's score uses only news out by 9:25 New York, traded from the official " + "open. Returns are relative to the average stock. Directions fixed on 2016-2021 (|t| >= 2), judged " + f"on 2022-2026; book costs {COST_BP:g} bp per round trip.", "", + "### The books", "", books.to_markdown(index=False), "", + "### Cells: sentiment x past performance", "", + show.sort_values(["target", "past", "sentiment", "past_tercile"]).to_markdown(index=False), "", + f"{len(rules)} cells pass on the training years; " + f"{sum(1 for r in rules if r['t_test'] is not None and np.sign(r['t_test']) == r['direction'])} keep " + "their sign on the test years."] + (out / "sentiment.md").write_text("\n".join(lines)) + return {"rules": len(rules), "books": books.to_dict("records")} diff --git a/tests/test_news_sentiment.py b/tests/test_news_sentiment.py new file mode 100644 index 000000000..fabf69d19 --- /dev/null +++ b/tests/test_news_sentiment.py @@ -0,0 +1,79 @@ +"""News sentiment study: scoring, the 9:25 cutoff, past terciles, and finding a planted effect.""" +import json + +import numpy as np +import pandas as pd + +from qtrade.research import news_sentiment as N + + +def test_score_text(): + assert N.score_text("Acme beats estimates, raises guidance") > 1 + assert N.score_text("Acme misses, cuts outlook; downgraded") < -1 + assert N.score_text("Acme to present at a conference") == 0 + + +def test_cutoff_and_panel(): + dates = pd.bdate_range("2024-01-01", periods=5) + sc = pd.DataFrame({"created_at": pd.to_datetime(["2024-01-02 09:20", "2024-01-02 09:27", "2024-01-02 20:00"]) + .tz_localize("America/New_York").tz_convert("UTC"), + "ticker": ["A", "B", "A"], "score": [1.0, -1.0, 0.5]}) + p = N.sentiment_panel(sc, dates, ["A", "B"]) + assert p.loc["2024-01-02", "A"] == 1.0 # out by 9:25: traded that open + assert p.loc["2024-01-03", "B"] == -1.0 # 9:27: too late, next open + assert p.loc["2024-01-03", "A"] == 0.5 + + +def test_terciles(): + past = pd.DataFrame([[0.1, 0.0, -0.1, 0.05, -0.05, 0.2]], columns=list("abcdef")) + t = N.terciles(past, pd.DataFrame(True, index=past.index, columns=past.columns)) + assert t.loc[0, "c"] == 0 and t.loc[0, "f"] == 2 and t.loc[0, "b"] == 1 + + +def test_finds_a_planted_effect(tmp_path): + rng = np.random.default_rng(1) + dates = pd.bdate_range("2016-01-04", "2026-06-30") + tickers = [f"S{i}" for i in range(60)] + close = pd.DataFrame(np.exp(np.cumsum(rng.normal(0, 0.01, (len(dates), 60)), axis=0)) * 50, dates, tickers) + open_ = close.shift(1).fillna(close) * np.exp(rng.normal(0, 0.003, close.shape)) + # every day 6 stocks have news; good news on a past-month loser rises 50 bp open -> close + rows, ret = [], close / open_ - 1 + past21 = close.shift(1) / close.shift(22) - 1 + for i, d in enumerate(dates[30:], 30): + for t in rng.choice(tickers, 6, replace=False): + s = rng.choice(["beats estimates", "misses estimates"]) + rows.append({"created_at": (d + pd.Timedelta(hours=8)).tz_localize("America/New_York").tz_convert("UTC"), + "headline": f"{t} {s}", "summary": "", "symbols": t}) + loser = past21.loc[d, t] < past21.loc[d].quantile(1 / 3) + if s.startswith("beats") and loser: + close.loc[d, t] = open_.loc[d, t] * (1 + ret.loc[d, t] + 0.005) + news = pd.DataFrame(rows) + + class MD: + pass + + md = MD() + md.dates, md.tickers, md.close, md.open = dates, tickers, close, open_ + + class Ctx: + tradable = pd.DataFrame(True, index=dates, columns=tickers) + + class Cfg: + class data: + cache_dir = str(tmp_path) + + (tmp_path / "news").mkdir() + news.assign(id=range(len(news)), updated_at=news["created_at"], author="", source="", url="") \ + .to_parquet(tmp_path / "news" / "news_2016-01.parquet") + out = tmp_path / "out" + out.mkdir() + N.run(md, Ctx, out, Cfg) + rules = json.loads((out / "sentiment_rules.json").read_text())["rules"] + hit = [r for r in rules if r["past"] == "past_21d" and r["past_tercile"] == "loser" + and r["sentiment"] == "positive" and r["target"] == "intraday"] + assert hit and hit[0]["direction"] == 1 and hit[0]["t_test"] > 2 + + +def test_strategy_without_rules_is_empty(): + s = N.strategy([], None, {}, {}, "intraday") + assert s.empty and N._period(s, N.TRAIN).empty and N.perf(s, 1)["days"] == 0 diff --git a/tests/test_sentiment_sheet.py b/tests/test_sentiment_sheet.py new file mode 100644 index 000000000..0a6dd9ac1 --- /dev/null +++ b/tests/test_sentiment_sheet.py @@ -0,0 +1,46 @@ +"""The $0 sentiment tracker's bookkeeping.""" +import numpy as np +import pandas as pd + +from qtrade.intraday import sentiment_sheet as S + + +def test_pick_rules_prefers_those_holding_up(): + spec = {"rules": [ + {"target": "intraday", "direction": 1, "t_test": 2.5, "sentiment": "positive", "past": "past_21d", + "past_tercile": "loser"}, + {"target": "intraday", "direction": -1, "t_test": 1.0, "sentiment": "negative", "past": "past_1d", + "past_tercile": "winner"}, + {"target": "hold_5d", "direction": 1, "t_test": 3.0, "sentiment": "positive", "past": "past_1d", + "past_tercile": "loser"}]} + rules, why = S.pick_rules(spec) + assert len(rules) == 1 and rules[0]["past_tercile"] == "loser" and "held up" in why + spec["rules"][0]["t_test"] = -1.0 + rules, why = S.pick_rules(spec) + assert len(rules) == 2 and "none held up" in why + + +def test_day_sentiment_window(): + sc = pd.DataFrame({"created_at": pd.to_datetime(["2026-11-30 13:00", "2026-11-30 14:30", "2026-11-29 12:00"], + utc=True), "ticker": ["A", "A", "B"], "score": [1.0, 0.0, -1.0]}) + s = S.day_sentiment(sc, pd.Timestamp("2026-11-29 14:25", tz="UTC"), pd.Timestamp("2026-11-30 14:25", tz="UTC")) + assert list(s.index) == ["A"] and s.loc["A", "score"] == 1.0 and s.loc["A", "articles"] == 1 + + +def test_legs_and_settle(): + days = pd.bdate_range("2026-10-01", periods=30) + close = pd.DataFrame({t: np.linspace(100, 100 * (1 + g), 30) for t, g in + [("A", -0.2), ("B", 0.0), ("C", 0.2), ("D", 0.01), ("E", -0.01), ("F", 0.1)]}, index=days) + day = days[-1] + past = S.past_terciles(close, day) + assert past.loc["A", "past_21d_t"] == 0 and past.loc["C", "past_21d_t"] == 2 + sent = pd.DataFrame({"score": [1.0, -1.0], "articles": [2, 1]}, index=["A", "C"]) + rules = [{"sentiment": "positive", "past": "past_21d", "past_tercile": "loser", "direction": 1}, + {"sentiment": "negative", "past": "past_21d", "past_tercile": "winner", "direction": -1}] + lg = S.legs(rules, sent, past) + assert list(lg["Symbol"]) == ["A", "C"] + open_ = pd.Series(100.0, index=close.columns) + cl = pd.Series([102.0, 100, 97, 100, 100, 101], index=close.columns) # average stock 0% + out, pnl = S.settle(lg, open_, cl, 10_000.0) + assert list(out["Side"]) == ["long", "short"] + assert round(pnl, 2) == round(5000 * 0.02 + 5000 * 0.03, 2)