fix(market): refuse unpriced/unsupported --ticker, gap rows for unsupported seed tickers, missing-overlap re-pull, null returns across window gaps

This commit is contained in:
kert
2026-11-13 00:52:16 -05:00
parent 37dc7d74b5
commit e250c516ed
4 changed files with 229 additions and 9 deletions

View File

@@ -12,6 +12,7 @@ nothing else is written.
from __future__ import annotations
import dataclasses
import datetime as dt
from collections import Counter
from typing import Any
@@ -353,6 +354,10 @@ def _merge_gap(existing: str, issues: dict[str, str], fetched: set[str]) -> str:
return " | ".join(kept[t] for t in sorted(kept))
def _has_day(records: list[dict[str, Any]], day: Any) -> bool:
return any(str(r["date"])[:10] == day.isoformat() for r in records)
@app.command()
def prices(
ticker: list[str] = typer.Option(
@@ -399,6 +404,7 @@ def prices(
import duckdb
skipped: dict[str, str] = {}
con = _read()
try:
state = _or_empty(tiingo.last_pulls, con, {})
@@ -410,6 +416,7 @@ def prices(
benchmarks_on=benchmarks,
used=budget.symbols,
supported=supported,
skipped=skipped,
),
con,
None,
@@ -426,6 +433,7 @@ def prices(
benchmarks_on=benchmarks or universe,
used=budget.symbols,
supported=supported,
skipped=skipped,
)
mem.close()
@@ -434,6 +442,8 @@ def prices(
f"symbols used, {budget.remaining_symbols} remaining; requests today "
f"{budget.day_counts.get(day.isoformat(), 0)}/{tiingo.DAILY_REQUESTS}"
)
for t, why in sorted(skipped.items()):
typer.echo(f"skipped {t}: {why}")
if dry_run:
for i, t in enumerate(targets, 1):
seen = state.get(t.ticker)
@@ -444,7 +454,10 @@ def prices(
return
fetched: dict[str, list[Any]] = {}
issues: dict[str, str] = {}
# an unsupported ticker is a gap; a priced=false record is only refused
issues: dict[str, str] = {
t: why for t, why in skipped.items() if why == tiingo.NOT_SUPPORTED
}
n_downloaded = 0
cl = http.client("tiingo", key)
try:
@@ -470,6 +483,22 @@ def prices(
typer.echo(f"budget: stopped, {exc}")
break
n_downloaded += 1
if last and records and not _has_day(records, last[0]):
back = last[0] - dt.timedelta(days=10)
typer.echo(
f"{t.ticker}: overlap day {last[0]} missing in the pull; "
f"re-pulling from {back}"
)
records, path = tiingo.fetch_eod(
cl,
t.ticker,
back,
day,
pacer=pacer,
budget=budget,
today=day,
refresh=refresh,
)
if records is None:
issues[t.ticker] = "not found at Tiingo"
typer.echo(f"{t.ticker}: not found at Tiingo")

View File

@@ -21,7 +21,7 @@ import json
import zipfile
from collections import defaultdict
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from datetime import date
from pathlib import Path
from typing import Any
@@ -55,6 +55,8 @@ FLOOR = date(1993, 1, 29)
MONTHLY_SYMBOLS = 450
DAILY_REQUESTS = 950
PACE_SECONDS = 75.0
NOT_SUPPORTED = "not on Tiingo's supported list"
NOT_PRICED = "symbol record only (priced=false), never sent to Tiingo"
_STRENGTH = {"revenue_exposure": 0, "risk_factor": 1, "mention": 2}
@@ -256,7 +258,7 @@ def to_prices(
ret_raw = (close + div) * split / float(prev["close"]) - 1.0
prev = rec
day = date.fromisoformat(str(rec["date"])[:10])
if overlap is not None and day == overlap:
if overlap is not None and day <= overlap:
continue
rows.append(
PriceRow(
@@ -407,13 +409,15 @@ def universe(
cap: int = MONTHLY_SYMBOLS,
supported: Mapping[str, Any] | None = None,
seed_order: Sequence[str] | None = None,
skipped: dict[str, str] | None = None,
) -> list[tuple[str, str]]:
"""``(ticker, entity_key)`` in rank order: the benchmarks, the seed
securities in seed order, then the securities of entities with a
filing-text (``fts``) link, ranked by strongest link, number of distinct
link targets and newest 10-K. SIC-only entities and unsupported or
unpriced tickers are excluded; at most *cap* symbols not already in
*used* are returned."""
*used* are returned. Each unsupported ticker is recorded in *skipped*
(``{ticker: reason}``) so the caller can turn it into a gap."""
by_entity: dict[str, list[str]] = defaultdict(list)
for s in read_securities(con):
if s.priced:
@@ -451,7 +455,11 @@ def universe(
seen: set[str] = set()
fresh = 0
for ticker, key in ranked:
if ticker in seen or (supported is not None and ticker not in supported):
if ticker in seen:
continue
if supported is not None and ticker not in supported:
if skipped is not None:
skipped[ticker] = NOT_SUPPORTED
continue
if ticker not in used:
if fresh >= cap:
@@ -487,8 +495,12 @@ def plan(
supported: Mapping[str, Any] | None = None,
cap: int = MONTHLY_SYMBOLS,
seed_order: Sequence[str] | None = None,
skipped: dict[str, str] | None = None,
) -> list[Target]:
"""Benchmarks, then the named tickers, then the ranked universe."""
"""Benchmarks, then the named tickers, then the ranked universe. A named
ticker that is a ``priced=false`` symbol record, or is not on Tiingo's
supported list, is refused like a universe member (reason in *skipped*)."""
skipped = {} if skipped is None else skipped
names: list[tuple[str, str]] = []
if benchmarks_on:
names += [(t, f"index:{t}") for t in BENCHMARKS]
@@ -497,10 +509,21 @@ def plan(
secs[s.ticker].append(s)
for t in tickers:
t = t.upper()
if secs.get(t) and not any(x.priced for x in secs[t]):
skipped[t] = NOT_PRICED
continue
if supported is not None and t not in supported:
skipped[t] = NOT_SUPPORTED
continue
names.append((t, secs[t][0].entity_key if secs.get(t) else ""))
if universe_on:
names += universe(
con, used=used, cap=cap, supported=supported, seed_order=seed_order
con,
used=used,
cap=cap,
supported=supported,
seed_order=seed_order,
skipped=skipped,
)
out: list[Target] = []
seen: set[str] = set()
@@ -523,7 +546,17 @@ def plan(
def clip_windows(
rows: Sequence[PriceRow], windows: Sequence[tuple[date | None, date | None]]
) -> list[PriceRow]:
"""Rows inside any of *windows* (all rows when there is none)."""
"""Rows inside any of *windows* (all rows when there is none). The first
kept row after dropped rows has no valid predecessor (a window gap, or a
different company's ticker), so its returns are nulled."""
if not windows:
return list(rows)
return [r for r in rows if any(clip([r], a, b) for a, b in windows)]
out: list[PriceRow] = []
dropped = False
for r in rows:
if any(clip([r], a, b) for a, b in windows):
out.append(replace(r, ret=None, ret_raw=None) if dropped else r)
dropped = False
else:
dropped = True
return out

View File

@@ -645,6 +645,7 @@ def px(env, monkeypatch, tmp_path):
"SPY,NYSE,ETF,USD,1993-01-29,2026-11-12",
"XLV,NYSE,ETF,USD,1998-12-22,2026-11-12",
"IHF,NYSE,ETF,USD,2006-05-05,2026-11-12",
"ZZZ,NYSE,Stock,USD,2000-01-01,2026-11-12",
)
def prices_for(m):
@@ -919,3 +920,87 @@ def test_or_empty_reraises_other_errors():
with pytest.raises(RuntimeError):
mk._or_empty(boom, None, {})
def test_prices_ticker_refuses_unpriced_record_without_a_request(px):
c, _, _, _, seen, _, state = px
T.ensure_tables(c)
T.write_securities(
c, "K9", [T.SecurityRow("K9", "AAA", "NYSE", None, None, "s", False)]
)
res = runner.invoke(app, ["market", "prices", "--ticker", "AAA", "--write"])
assert res.exit_code == 0, res.output
assert "skipped AAA: symbol record only" in res.output
assert _price_requests(seen) == [] and _count(c, "market.price_daily") == 0
assert not (state / "tiingo-2026-11.json").exists()
assert T.read_gaps(c) == []
def test_prices_unsupported_named_ticker_is_gap_not_request(px):
c, _, _, _, seen, _, _ = px
res = runner.invoke(app, ["market", "prices", "--ticker", "QQQQ", "--write"])
assert "skipped QQQQ: not on Tiingo's supported list" in res.output
assert _price_requests(seen) == []
(gap,) = T.read_gaps(c)
assert gap.note == "QQQQ: not on Tiingo's supported list"
def test_prices_universe_records_unsupported_seed_ticker_gap(px):
c, _, _, _, seen, _, _ = px
T.ensure_tables(c)
T.write_securities(
c, "0001800682", [T.SecurityRow("0001800682", "CANO", "NYSE", None, None, "s")]
)
res = runner.invoke(app, ["market", "prices", "--universe", "--write"])
assert res.exit_code == 0, res.output
assert "skipped CANO: not on Tiingo's supported list" in res.output
assert all("/CANO/" not in r.url.path for r in seen)
(gap,) = T.read_gaps(c)
assert gap.source == "tiingo:prices"
assert gap.note == "CANO: not on Tiingo's supported list"
# rerun with everything already priced today keeps the gap
again = runner.invoke(app, ["market", "prices", "--universe", "--write"])
assert again.exit_code == 0
assert [g.note for g in T.read_gaps(c)] == [gap.note]
def test_prices_missing_overlap_day_repulls_further_back(px, monkeypatch):
c, _, _, _, seen, _, _ = px
cmd = ["market", "prices", "--ticker", "AAA", "--write"]
assert runner.invoke(app, cmd).exit_code == 0
monkeypatch.setattr(tiingo, "today", lambda: date(2026, 11, 13))
z = _supported_zip("AAA,NYSE,Stock,USD,2000-01-01,2026-11-12")
def eod(m):
# the 2024-01-04 overlap day is absent from the narrow pull
start = next(r for r in seen[::-1] if "/prices" in r.url.path).url.params[
"startDate"
]
if start == "2024-01-04":
return httpx.Response(200, json=[_eod("2024-01-05", 54.45)])
return httpx.Response(
200, json=[_eod("2024-01-03", 55), _eod("2024-01-05", 60.5)]
)
handler = _handler(
[
(r"supported_tickers", lambda m: httpx.Response(200, content=z)),
(r"/daily/AAA/prices", eod),
]
)
def record(request):
seen.append(request)
return handler(request)
monkeypatch.setattr(
http,
"client",
lambda source, key=None: httpx.Client(transport=httpx.MockTransport(record)),
)
res = runner.invoke(app, cmd)
assert res.exit_code == 0, res.output
assert "overlap day 2024-01-04 missing" in res.output
assert "re-pulling from 2023-12-25" in res.output
row = {r.day: r for r in T.read_prices(c, "AAA")}[date(2024, 1, 5)]
assert row.ret == pytest.approx(60.5 / 55 - 1)

View File

@@ -425,3 +425,76 @@ def test_plan_deduplicates_names():
)
assert [t.ticker for t in got] == ["SPY", "XLV", "IHF"]
assert TI.clip_windows([], []) == []
def test_plan_refuses_unpriced_and_unsupported_named_tickers():
con = duckdb.connect(":memory:")
T.ensure_tables(con)
T.write_securities(
con, "C", [T.SecurityRow("C", "CI", "NYSE", None, None, "s", False)]
)
T.write_securities(
con,
"E",
[
T.SecurityRow("E", "ANTM", "NYSE", None, None, "s", False),
T.SecurityRow("E", "ELV", "NYSE", None, None, "s", True),
],
)
skipped: dict[str, str] = {}
got = TI.plan(
con,
tickers=["ci", "ANTM", "ELV", "NOPE"],
universe_on=False,
benchmarks_on=False,
used=set(),
supported={"CI": (None, None), "ELV": (None, None)},
skipped=skipped,
)
assert [t.ticker for t in got] == ["ELV"]
assert skipped == {
"CI": TI.NOT_PRICED,
"ANTM": TI.NOT_PRICED,
"NOPE": TI.NOT_SUPPORTED,
}
def test_universe_records_unsupported_priced_seed_tickers():
con = _universe_db()
skipped: dict[str, str] = {}
supported = {k: v for k, v in SUPPORTED.items() if k != "REVCO"}
TI.universe(
con, used=set(), supported=supported, seed_order=["SEED"], skipped=skipped
)
assert skipped == {"REVCO": TI.NOT_SUPPORTED, "GONECO": TI.NOT_SUPPORTED}
def test_clip_windows_nulls_first_return_after_each_gap():
recs = [rec(f"2024-01-0{d}", 100 + d) for d in range(1, 8)]
rows = pull("X", recs)
wins = [(date(2024, 1, 1), date(2024, 1, 2)), (date(2024, 1, 5), date(2024, 1, 7))]
kept = TI.clip_windows(rows, wins)
assert [r.day.day for r in kept] == [1, 2, 5, 6, 7]
assert [r.ret is None for r in kept] == [True, False, True, False, False]
assert kept[2].ret_raw is None and kept[1].ret_raw is not None
# a single later window: its first row also lost its predecessor
only = TI.clip_windows(rows, [(date(2024, 1, 3), None)])
assert only[0].ret is None and only[1].ret is not None
def test_to_prices_drops_days_up_to_overlap():
recs = [rec("2024-01-02", 100), rec("2024-01-03", 110), rec("2024-01-05", 121)]
rows = pull("X", recs, overlap=date(2024, 1, 4))
assert [r.day for r in rows] == [date(2024, 1, 5)]
assert rows[0].ret == pytest.approx(0.1)
def test_universe_dedupes_repeated_seed_entries():
con = _universe_db()
got = [
t
for t, _ in TI.universe(
con, used=set(), supported=SUPPORTED, seed_order=["SEED", "SEED"]
)
]
assert got.count("SEEDCO") == 1