Coverage for portfolio/filing_signals.py: 100%
136 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Signal tables of V6.6.4's round 4E: session x name, higher is better, each known at that session's close.
3Every event (a filing, an announcement, an insider purchase) becomes visible at the first session strictly after its date, so a filing made during a session never informs
4that session. `known` rows already hold the bar from before the session, as everywhere in the research pipeline. Nothing here is fitted, and a name without the history a signal
5needs is NaN, never a number.
6"""
8from __future__ import annotations
10from typing import Any
12import numpy as np
13import pandas as pd
16def _dates(values) -> pd.Series:
17 return pd.to_datetime(pd.Series(values), errors="coerce", utc=True).dt.tz_localize(None).dt.normalize()
20def _positions(index: pd.Index, dates: pd.Series, *, side: str) -> np.ndarray:
21 """Row of each date among the (ISO-string) session index; `right` is the first session strictly after the date, `left` the first on or after it."""
22 sessions = pd.to_datetime(pd.Index(index)).tz_localize(None) if not isinstance(index, pd.DatetimeIndex) else index
23 return sessions.searchsorted(pd.DatetimeIndex(dates), side=side)
26def events_to_sessions(events: pd.DataFrame, index: pd.Index, columns: pd.Index, *, date: str, value: str, limit: int | None) -> pd.DataFrame:
27 """The newest `value` per name as of each session, from rows with a `date` and a `ticker`. Visible from the first session strictly after `date`; a later event
28 at the same row wins; carried forward at most `limit` rows."""
29 table = pd.DataFrame(np.nan, index=index, columns=columns)
30 if events is None or len(events) == 0:
31 return table
32 frame = pd.DataFrame({"ticker": events["ticker"].to_numpy(), "date": _dates(events[date]).to_numpy(), "value": pd.to_numeric(events[value], errors="coerce").to_numpy()})
33 frame = frame[frame["date"].notna() & frame["value"].notna() & frame["ticker"].isin(columns)].sort_values("date", kind="stable")
34 if frame.empty:
35 return table
36 rows = _positions(index, frame["date"], side="right")
37 keep = rows < len(index)
38 columns_at = {name: position for position, name in enumerate(columns)}
39 values = table.to_numpy(dtype=float, copy=True)
40 for row, ticker, number in zip(rows[keep], frame["ticker"].to_numpy()[keep], frame["value"].to_numpy()[keep], strict=False):
41 values[row, columns_at[ticker]] = number
42 return pd.DataFrame(values, index=index, columns=columns).ffill(limit=limit)
45def similarity_table(rows: pd.DataFrame, index: pd.Index, columns: pd.Index, *, max_age: int = 130) -> pd.DataFrame:
46 """The newest 10-K or 10-Q's similarity to the same form a year earlier (Cohen, Malloy, Nguyen): high means the filing is unchanged. Blank after `max_age` sessions without a newer one."""
47 return events_to_sessions(rows, index, columns, date="filed", value="similarity", limit=max_age)
50def announcement_proximity(rows: pd.DataFrame, index: pd.Index, columns: pd.Index, *, window_days: int = 14) -> pd.DataFrame:
51 """1.0 during the `window_days` calendar days before a name's expected announcement (about ten sessions), 0.0 otherwise, NaN for a name with no earlier announcement.
52 The expected date is an announcement 52 weeks earlier (Frazzini and Lamont's announcement premium), so no filing at or after the session is read. An expected date beyond the last
53 session flags only the sessions that really lie inside its window."""
54 table = pd.DataFrame(np.nan, index=index, columns=columns)
55 if rows is None or len(rows) == 0:
56 return table
57 frame = pd.DataFrame({"ticker": rows["ticker"].to_numpy(), "date": _dates(rows["accepted"]).to_numpy()})
58 frame = frame[frame["date"].notna() & frame["ticker"].isin(columns)]
59 expected = frame["date"] + pd.Timedelta(days=364)
60 values = table.to_numpy(dtype=float, copy=True)
61 columns_at = {name: position for position, name in enumerate(columns)}
62 first_seen: dict[str, int] = {}
63 for date, ticker in zip(_positions(index, frame["date"], side="right"), frame["ticker"], strict=False):
64 first_seen[ticker] = min(first_seen.get(ticker, len(index)), int(date))
65 for ticker, first in first_seen.items():
66 values[first:, columns_at[ticker]] = 0.0 # a name with an announcement on record is measurable from the session after it
67 ends = _positions(index, expected, side="left")
68 starts = _positions(index, expected - pd.Timedelta(days=window_days), side="left")
69 for low, end, ticker in zip(starts, ends, frame["ticker"], strict=False):
70 if low < end:
71 values[int(low):int(end), columns_at[ticker]] = 1.0
72 return pd.DataFrame(values, index=index, columns=columns)
75def announcement_return(rows: pd.DataFrame, known: pd.DataFrame, *, days: int = 3, decay: int = 60, bench: str = "SPY") -> pd.DataFrame:
76 """The abnormal return over `days` rows from the announcement (Brandt, Kishore, Santa-Clara and Venkatachalam), held for `decay` rows once it is complete.
77 Row `start` holds the close before the announcement day, row `start + days` the close of its last reaction day. Blank until those days have passed, and for `bench` itself."""
78 table = pd.DataFrame(np.nan, index=known.index, columns=known.columns)
79 if rows is None or len(rows) == 0 or bench not in known.columns:
80 return table
81 frame = pd.DataFrame({"ticker": rows["ticker"].to_numpy(), "date": _dates(rows["accepted"]).to_numpy()})
82 frame = frame[frame["date"].notna() & frame["ticker"].isin(known.columns) & (frame["ticker"] != bench)].sort_values("date", kind="stable")
83 starts = _positions(known.index, frame["date"], side="left")
84 prices = known.to_numpy(dtype=float)
85 benchmark = known[bench].to_numpy(dtype=float)
86 columns_at = {name: position for position, name in enumerate(known.columns)}
87 values = table.to_numpy(dtype=float, copy=True)
88 for start, ticker in zip(starts, frame["ticker"], strict=False):
89 end = int(start) + days
90 if start < 1 or end >= len(known.index):
91 continue
92 column = columns_at[ticker]
93 before, after = prices[start, column], prices[end, column]
94 bench_before, bench_after = benchmark[start], benchmark[end]
95 if not (np.isfinite(before) and np.isfinite(after) and np.isfinite(bench_before) and np.isfinite(bench_after) and before > 0.0 and bench_before > 0.0):
96 continue
97 values[end:min(len(known.index), end + decay), column] = after / before - bench_after / bench_before
98 return pd.DataFrame(values, index=known.index, columns=known.columns)
101def same_month_seasonality(known: pd.DataFrame, *, years: int = 7, min_years: int = 5) -> pd.DataFrame:
102 """The mean return of this calendar month over the previous `years` years (Heston and Sadka), needing `min_years` of them. Only completed months of earlier years are read."""
103 dates = pd.to_datetime(pd.Index(known.index)).tz_localize(None)
104 month = dates.to_period("M")
105 last = known.groupby(month).last()
106 full = pd.period_range(last.index.min(), last.index.max(), freq="M")
107 monthly = last.reindex(full).pct_change(fill_method=None).replace([np.inf, -np.inf], np.nan)
108 stack = np.stack([monthly.shift(12 * k).to_numpy(dtype=float) for k in range(1, years + 1)])
109 count = np.isfinite(stack).sum(axis=0)
110 mean = np.where(count >= min_years, np.nansum(stack, axis=0) / np.where(count > 0, count, 1), np.nan)
111 seasonal = pd.DataFrame(mean, index=full, columns=known.columns)
112 table = seasonal.reindex(month)
113 table.index = known.index
114 return table.where(known.notna())
117def opportunistic_buying(trades: pd.DataFrame, index: pd.Index, columns: pd.Index, *, routine_years: int = 3, window: int = 63) -> pd.DataFrame:
118 """Open-market purchases (code P) by owners who weren't routine buyers (Cohen, Malloy, Pomorski): an owner who bought in the same calendar month in each of the previous
119 `routine_years` years is routine and left out. The value over the last `window` rows, logged. Dated by `filed`; 0.0 means no such purchase."""
120 table = pd.DataFrame(0.0, index=index, columns=columns)
121 if trades is None or len(trades) == 0:
122 return table
123 frame = pd.DataFrame({
124 "ticker": trades["ticker"].to_numpy(), "owner": trades["owner"].to_numpy(), "code": trades["code"].to_numpy(),
125 "filed": _dates(trades["filed"]).to_numpy(), "value": pd.to_numeric(trades["value"], errors="coerce").to_numpy(),
126 })
127 frame = frame[(frame["code"] == "P") & frame["filed"].notna() & frame["value"].notna() & (frame["value"] > 0.0) & frame["ticker"].isin(columns)]
128 if frame.empty:
129 return table
130 stamp = pd.DatetimeIndex(frame["filed"])
131 frame = frame.assign(year=stamp.year, month=stamp.month)
132 seen = set(zip(frame["ticker"], frame["owner"], frame["year"], frame["month"], strict=False))
133 routine = np.array([
134 all((ticker, owner, year - gap, month) in seen for gap in range(1, routine_years + 1))
135 for ticker, owner, year, month in zip(frame["ticker"], frame["owner"], frame["year"], frame["month"], strict=False)
136 ])
137 kept = frame[~routine] # never empty: the first purchase of an owner in a month has no earlier year to repeat
138 daily = pd.DataFrame(0.0, index=index, columns=columns)
139 rows = _positions(index, kept["filed"], side="right")
140 values = daily.to_numpy(dtype=float, copy=True)
141 columns_at = {name: position for position, name in enumerate(columns)}
142 for row, ticker, value in zip(rows, kept["ticker"], kept["value"], strict=False):
143 if row < len(index):
144 values[row, columns_at[ticker]] += float(value)
145 daily = pd.DataFrame(values, index=index, columns=columns)
146 return np.log1p(daily.rolling(window, min_periods=1).sum())
149def cash_profitability(fundamentals: pd.DataFrame, index: pd.Index, columns: pd.Index, *, max_age: int = 400) -> pd.DataFrame:
150 """Trailing operating cash flow over assets (Ball et al.), each as last filed before the session."""
151 flow = events_to_sessions(fundamentals[fundamentals["field"] == "ttm_operating_cash_flow"], index, columns, date="filed", value="value", limit=max_age)
152 assets = events_to_sessions(fundamentals[fundamentals["field"] == "assets"], index, columns, date="filed", value="value", limit=max_age)
153 return (flow / assets.where(assets > 0.0)).replace([np.inf, -np.inf], np.nan)
156def fred_as_known(series: dict[str, Any], index: pd.Index, *, keys: tuple[str, ...] = ("treasury_10yr", "treasury_3mo", "credit_spread_baa10y"), lag_sessions: int = 1) -> pd.DataFrame:
157 """FRED series (`{key: Series by date}`) as the session knows them: carried across days with no mark, then read `lag_sessions` late, since FRED's daily marks post after the equity close."""
158 columns = {}
159 for key in keys:
160 values = series.get(key)
161 if values is None or len(values) == 0:
162 columns[key] = pd.Series(np.nan, index=index)
163 continue
164 values = values.sort_index()
165 columns[key] = values.reindex(values.index.union(index)).ffill().reindex(index).shift(lag_sessions)
166 return pd.DataFrame(columns, index=index)
169def term_credit_timing(fred_table: pd.DataFrame, known: pd.DataFrame, *, ticker: str = "SPY", window: int = 252) -> pd.DataFrame:
170 """1.0 on `ticker` while the term spread (10 years less 3 months) is positive and the Baa credit spread is at or below its own trailing median, else 0.0. NaN when a rate is missing."""
171 table = pd.DataFrame(np.nan, index=known.index, columns=known.columns)
172 needed = ("treasury_10yr", "treasury_3mo", "credit_spread_baa10y")
173 if ticker not in table.columns or any(name not in fred_table for name in needed):
174 return table
175 rates = pd.DataFrame({name: fred_table[name] for name in needed}).reindex(known.index) # a FRED mapping {key: series}, or a frame with those columns
176 term = rates["treasury_10yr"] - rates["treasury_3mo"]
177 credit = rates["credit_spread_baa10y"]
178 median = credit.rolling(window, min_periods=window // 2).median()
179 measurable = term.notna() & credit.notna() & median.notna() & known[ticker].notna()
180 table[ticker] = ((term > 0.0) & (credit <= median)).astype(float).where(measurable)
181 return table
184def cross_asset_trend(known: pd.DataFrame, tickers: tuple[str, ...] | list[str], *, long: int = 252, skip: int = 21) -> pd.DataFrame:
185 """1.0 where the 12-1 month return (`long` rows back to `skip` rows back) is positive, else 0.0; NaN without that history. Only the named assets."""
186 table = pd.DataFrame(np.nan, index=known.index, columns=known.columns)
187 for ticker in tickers:
188 if ticker in table.columns:
189 ratio = known[ticker].shift(skip) / known[ticker].shift(long) - 1.0
190 table[ticker] = (ratio > 0.0).astype(float).where(ratio.notna())
191 return table