Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/research.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 }})"
Expand Down
44 changes: 44 additions & 0 deletions .github/workflows/sentiment-sheet.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions qtrade/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
]

Expand Down
214 changes: 214 additions & 0 deletions qtrade/intraday/sentiment_sheet.py
Original file line number Diff line number Diff line change
@@ -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()
3 changes: 3 additions & 0 deletions qtrade/research/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading