alphasift 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alphasift/__init__.py +52 -0
- alphasift/__main__.py +7 -0
- alphasift/audit.py +191 -0
- alphasift/candidate_context.py +738 -0
- alphasift/cli.py +2797 -0
- alphasift/config.py +705 -0
- alphasift/context.py +672 -0
- alphasift/daily.py +1256 -0
- alphasift/daily_brief.py +593 -0
- alphasift/daily_report.py +1115 -0
- alphasift/daily_report_html.py +1257 -0
- alphasift/doctor.py +1123 -0
- alphasift/dsa.py +302 -0
- alphasift/dsa_adapter.py +178 -0
- alphasift/dsa_provider.py +192 -0
- alphasift/evaluate.py +2418 -0
- alphasift/filter.py +517 -0
- alphasift/hotspot.py +1713 -0
- alphasift/industry.py +959 -0
- alphasift/llm_client.py +349 -0
- alphasift/market_digest.py +284 -0
- alphasift/market_news.py +446 -0
- alphasift/market_regime.py +578 -0
- alphasift/markets.py +160 -0
- alphasift/mcp.py +720 -0
- alphasift/models.py +315 -0
- alphasift/normalize.py +113 -0
- alphasift/notify.py +2608 -0
- alphasift/overview.py +225 -0
- alphasift/pack.py +1470 -0
- alphasift/pack_features.py +431 -0
- alphasift/pattern_replay.py +1449 -0
- alphasift/patterns/bottom_volume_yang.yaml +32 -0
- alphasift/patterns/box_breakout.yaml +36 -0
- alphasift/patterns/double_bottom_breakout.yaml +38 -0
- alphasift/patterns/ma20_shrink_pullback.yaml +37 -0
- alphasift/patterns/shooting_star_confirm.yaml +49 -0
- alphasift/patterns/single_yang_hold.yaml +44 -0
- alphasift/patterns/steady_trend_breakout.yaml +39 -0
- alphasift/patterns/three_white_soldiers.yaml +72 -0
- alphasift/patterns/three_white_soldiers_pullback.yaml +91 -0
- alphasift/patterns.py +1233 -0
- alphasift/performance_history.py +297 -0
- alphasift/pipeline.py +1010 -0
- alphasift/post_analysis.py +337 -0
- alphasift/ranker.py +990 -0
- alphasift/report.py +379 -0
- alphasift/result_schema.py +179 -0
- alphasift/risk.py +452 -0
- alphasift/run_history.py +164 -0
- alphasift/scorer.py +597 -0
- alphasift/server.py +680 -0
- alphasift/snapshot.py +1025 -0
- alphasift/snapshot_us.py +280 -0
- alphasift/snapshot_yahoo.py +358 -0
- alphasift/source_guard.py +70 -0
- alphasift/source_history.py +306 -0
- alphasift/store.py +294 -0
- alphasift/strategies/balanced_alpha.yaml +76 -0
- alphasift/strategies/blue_chip_income.yaml +87 -0
- alphasift/strategies/capital_heat.yaml +74 -0
- alphasift/strategies/dual_low.yaml +80 -0
- alphasift/strategies/global_value.yaml +65 -0
- alphasift/strategies/low_volatility_quality.yaml +95 -0
- alphasift/strategies/momentum_quality.yaml +81 -0
- alphasift/strategies/oversold_reversal.yaml +75 -0
- alphasift/strategies/quality_value.yaml +80 -0
- alphasift/strategies/shrink_pullback.yaml +77 -0
- alphasift/strategies/us_momentum_quality.yaml +74 -0
- alphasift/strategies/volume_breakout.yaml +78 -0
- alphasift/strategy.py +1090 -0
- alphasift/strategy_cards.py +424 -0
- alphasift/strategy_templates.py +291 -0
- alphasift/timeutil.py +38 -0
- alphasift/valuation_kr.py +149 -0
- alphasift/workbench_ui.py +1051 -0
- alphasift-0.3.1.data/data/.env.example +151 -0
- alphasift-0.3.1.data/data/LICENSE +184 -0
- alphasift-0.3.1.data/data/SKILL.md +190 -0
- alphasift-0.3.1.data/data/agents/openai.yaml +7 -0
- alphasift-0.3.1.dist-info/METADATA +312 -0
- alphasift-0.3.1.dist-info/RECORD +86 -0
- alphasift-0.3.1.dist-info/WHEEL +5 -0
- alphasift-0.3.1.dist-info/entry_points.txt +2 -0
- alphasift-0.3.1.dist-info/licenses/LICENSE +184 -0
- alphasift-0.3.1.dist-info/top_level.txt +1 -0
alphasift/snapshot_us.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""US equity snapshot via yfinance.
|
|
3
|
+
|
|
4
|
+
Pluggable adapter for AlphaSift's L1 pipeline. Fetches a configurable
|
|
5
|
+
equity universe and returns the standard snapshot DataFrame schema.
|
|
6
|
+
|
|
7
|
+
Since the market registry, US runs use the Yahoo screener
|
|
8
|
+
(``snapshot_yahoo``) first; this per-ticker adapter is the fallback, and the
|
|
9
|
+
only path when ``ALPHASIFT_US_TICKERS`` pins an explicit list.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
15
|
+
from datetime import date, datetime
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
_SP500_WIKI_URL = "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
|
|
21
|
+
|
|
22
|
+
_DEFAULT_US_UNIVERSE = [
|
|
23
|
+
"AAPL", "MSFT", "NVDA", "AMZN", "GOOGL", "META", "TSLA", "BRK-B",
|
|
24
|
+
"AVGO", "JPM", "LLY", "V", "MA", "UNH", "XOM", "COST", "HD", "PG",
|
|
25
|
+
"JNJ", "ABBV", "WMT", "NFLX", "BAC", "KO", "CRM", "CVX", "MRK",
|
|
26
|
+
"PEP", "AMD", "TMO", "LIN", "ACN", "CSCO", "MCD", "ABT", "ADBE",
|
|
27
|
+
"WFC", "GE", "DHR", "TXN", "PM", "ISRG", "MS", "NEE", "INTU",
|
|
28
|
+
"DIS", "QCOM", "CAT", "NOW",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def fetch_us_universe(source: str = "auto") -> list[str]:
|
|
33
|
+
"""Return a list of US equity tickers.
|
|
34
|
+
|
|
35
|
+
Sources:
|
|
36
|
+
sp500 — scrape S&P 500 from Wikipedia
|
|
37
|
+
env — read ALPHASIFT_US_TICKERS (comma-separated)
|
|
38
|
+
default — hardcoded top-50 US large-caps
|
|
39
|
+
auto — try sp500 → env → default
|
|
40
|
+
"""
|
|
41
|
+
src = source.lower()
|
|
42
|
+
if src == "auto":
|
|
43
|
+
for s in ("sp500", "env", "default"):
|
|
44
|
+
try:
|
|
45
|
+
tickers = fetch_us_universe(s)
|
|
46
|
+
if tickers:
|
|
47
|
+
logger.info("US universe from %s: %d tickers", s, len(tickers))
|
|
48
|
+
return tickers
|
|
49
|
+
except Exception as e:
|
|
50
|
+
logger.debug("US universe source %s failed: %s", s, e)
|
|
51
|
+
return list(_DEFAULT_US_UNIVERSE)
|
|
52
|
+
|
|
53
|
+
if src == "sp500":
|
|
54
|
+
return _fetch_sp500_tickers()
|
|
55
|
+
elif src == "env":
|
|
56
|
+
raw = os.getenv("ALPHASIFT_US_TICKERS", "").strip()
|
|
57
|
+
if not raw:
|
|
58
|
+
raise ValueError("ALPHASIFT_US_TICKERS not set")
|
|
59
|
+
return [t.strip() for t in raw.split(",") if t.strip()]
|
|
60
|
+
elif src == "default":
|
|
61
|
+
return list(_DEFAULT_US_UNIVERSE)
|
|
62
|
+
else:
|
|
63
|
+
raise ValueError(f"Unknown US universe source: {source}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _fetch_sp500_tickers() -> list[str]:
|
|
67
|
+
tables = pd.read_html(_SP500_WIKI_URL)
|
|
68
|
+
for tbl in tables:
|
|
69
|
+
if "Symbol" in tbl.columns:
|
|
70
|
+
return sorted(tbl["Symbol"].dropna().str.strip().str.replace(".", "-", regex=False).tolist())
|
|
71
|
+
raise RuntimeError("Could not find Symbol column in S&P 500 Wikipedia table")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def fetch_us_snapshot(
|
|
75
|
+
tickers: list[str] | None = None,
|
|
76
|
+
*,
|
|
77
|
+
universe_source: str = "auto",
|
|
78
|
+
max_workers: int = 8,
|
|
79
|
+
) -> pd.DataFrame:
|
|
80
|
+
"""Fetch US equity snapshot in AlphaSift standard schema.
|
|
81
|
+
|
|
82
|
+
Uses yfinance to fetch current data for each ticker. Returns a
|
|
83
|
+
DataFrame matching the standard snapshot columns: code, name, price,
|
|
84
|
+
change_pct, amount, total_mv, pe_ratio, pb_ratio, volume_ratio,
|
|
85
|
+
turnover_rate, industry.
|
|
86
|
+
"""
|
|
87
|
+
import yfinance as yf
|
|
88
|
+
|
|
89
|
+
if tickers is None:
|
|
90
|
+
tickers = fetch_us_universe(universe_source)
|
|
91
|
+
|
|
92
|
+
logger.info("Fetching US snapshot for %d tickers", len(tickers))
|
|
93
|
+
|
|
94
|
+
hist_end = pd.Timestamp.now(tz="UTC").normalize().tz_localize(None) + pd.Timedelta(days=2)
|
|
95
|
+
hist_start = hist_end - pd.Timedelta(days=32)
|
|
96
|
+
data = yf.download(
|
|
97
|
+
tickers,
|
|
98
|
+
start=hist_start.strftime("%Y-%m-%d"),
|
|
99
|
+
end=hist_end.strftime("%Y-%m-%d"),
|
|
100
|
+
group_by="ticker",
|
|
101
|
+
auto_adjust=True,
|
|
102
|
+
progress=False,
|
|
103
|
+
threads=True,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
rows = []
|
|
107
|
+
quote_dates: list[str] = []
|
|
108
|
+
|
|
109
|
+
def _process_ticker(ticker: str) -> tuple[dict, str] | None:
|
|
110
|
+
try:
|
|
111
|
+
if len(tickers) == 1:
|
|
112
|
+
hist = data.copy()
|
|
113
|
+
if isinstance(hist.columns, pd.MultiIndex):
|
|
114
|
+
hist.columns = hist.columns.droplevel("Ticker")
|
|
115
|
+
else:
|
|
116
|
+
if ticker not in data.columns.get_level_values(0):
|
|
117
|
+
return None
|
|
118
|
+
hist = data[ticker].copy()
|
|
119
|
+
if hist.empty:
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
hist = hist[hist["Close"].notna()]
|
|
123
|
+
if len(hist) < 2:
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
raw_idx = hist.index[-1]
|
|
127
|
+
bar_date = ""
|
|
128
|
+
if isinstance(raw_idx, (pd.Timestamp, datetime, date)) or (
|
|
129
|
+
isinstance(raw_idx, str) and raw_idx.strip()
|
|
130
|
+
):
|
|
131
|
+
latest_ts = pd.to_datetime(raw_idx, errors="coerce")
|
|
132
|
+
if pd.notna(latest_ts):
|
|
133
|
+
if getattr(latest_ts, "tzinfo", None) is not None:
|
|
134
|
+
latest_ts = latest_ts.tz_convert("America/New_York")
|
|
135
|
+
bar_date = latest_ts.strftime("%Y-%m-%d")
|
|
136
|
+
|
|
137
|
+
latest = hist.iloc[-1]
|
|
138
|
+
prev = hist.iloc[-2]
|
|
139
|
+
price = float(latest["Close"])
|
|
140
|
+
prev_close = float(prev["Close"])
|
|
141
|
+
volume = float(latest["Volume"])
|
|
142
|
+
change_pct = ((price - prev_close) / prev_close * 100) if prev_close > 0 else 0.0
|
|
143
|
+
|
|
144
|
+
vol_20d = float(hist["Volume"].tail(20).mean())
|
|
145
|
+
vol_10d = float(hist["Volume"].tail(10).mean())
|
|
146
|
+
volume_ratio = (volume / vol_20d) if vol_20d > 0 else 1.0
|
|
147
|
+
|
|
148
|
+
info = yf.Ticker(ticker).fast_info
|
|
149
|
+
market_cap = getattr(info, "market_cap", None) or 0
|
|
150
|
+
shares = getattr(info, "shares", None) or 0
|
|
151
|
+
turnover_rate = (volume / shares * 100) if shares > 0 else 0.0
|
|
152
|
+
|
|
153
|
+
return (
|
|
154
|
+
{
|
|
155
|
+
"code": ticker,
|
|
156
|
+
"name": ticker,
|
|
157
|
+
"price": price,
|
|
158
|
+
"change_pct": round(change_pct, 2),
|
|
159
|
+
"amount": round(volume * price, 0),
|
|
160
|
+
"avg_amount": round(vol_10d * price, 0),
|
|
161
|
+
"avg_amount_usd": round(vol_10d * price, 0),
|
|
162
|
+
"total_mv": market_cap,
|
|
163
|
+
"circ_mv": market_cap,
|
|
164
|
+
"pe_ratio": None,
|
|
165
|
+
"pb_ratio": None,
|
|
166
|
+
"volume_ratio": round(volume_ratio, 2),
|
|
167
|
+
"turnover_rate": round(turnover_rate, 4),
|
|
168
|
+
"industry": "",
|
|
169
|
+
},
|
|
170
|
+
bar_date,
|
|
171
|
+
)
|
|
172
|
+
except Exception as e:
|
|
173
|
+
logger.debug("Failed to process %s: %s", ticker, e)
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
|
177
|
+
futures = {pool.submit(_process_ticker, t): t for t in tickers}
|
|
178
|
+
for future in as_completed(futures):
|
|
179
|
+
result = future.result()
|
|
180
|
+
if result:
|
|
181
|
+
row, bar_date = result
|
|
182
|
+
rows.append(row)
|
|
183
|
+
if bar_date:
|
|
184
|
+
quote_dates.append(bar_date)
|
|
185
|
+
|
|
186
|
+
if not rows:
|
|
187
|
+
raise RuntimeError("yfinance returned no valid data for any ticker")
|
|
188
|
+
|
|
189
|
+
df = pd.DataFrame(rows)
|
|
190
|
+
|
|
191
|
+
numeric_cols = [
|
|
192
|
+
"price", "change_pct", "amount", "avg_amount", "avg_amount_usd", "total_mv", "circ_mv",
|
|
193
|
+
"pe_ratio", "pb_ratio", "volume_ratio", "turnover_rate",
|
|
194
|
+
]
|
|
195
|
+
for col in numeric_cols:
|
|
196
|
+
if col in df.columns:
|
|
197
|
+
df[col] = pd.to_numeric(df[col], errors="coerce")
|
|
198
|
+
|
|
199
|
+
df = df.dropna(subset=["price"])
|
|
200
|
+
df = df[df["price"] > 0]
|
|
201
|
+
|
|
202
|
+
_enrich_info_fields(df)
|
|
203
|
+
|
|
204
|
+
df.attrs["snapshot_source"] = "yfinance"
|
|
205
|
+
df.attrs["market"] = "us"
|
|
206
|
+
if quote_dates:
|
|
207
|
+
df.attrs["quote_date"] = max(quote_dates)
|
|
208
|
+
logger.info("US snapshot: %d rows from yfinance", len(df))
|
|
209
|
+
return df
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _enrich_info_fields(df: pd.DataFrame) -> None:
|
|
213
|
+
"""Best-effort enrichment of pe_ratio, pb_ratio, industry from yfinance info."""
|
|
214
|
+
import yfinance as yf
|
|
215
|
+
|
|
216
|
+
from alphasift.snapshot_yahoo import sanitize_yahoo_pb
|
|
217
|
+
|
|
218
|
+
needs_pe = df["pe_ratio"].isna().sum() > len(df) * 0.5
|
|
219
|
+
if not needs_pe:
|
|
220
|
+
return
|
|
221
|
+
|
|
222
|
+
for idx in df.index:
|
|
223
|
+
ticker = df.at[idx, "code"]
|
|
224
|
+
try:
|
|
225
|
+
info = yf.Ticker(ticker).info
|
|
226
|
+
if pd.isna(df.at[idx, "pe_ratio"]) or df.at[idx, "pe_ratio"] == 0:
|
|
227
|
+
df.at[idx, "pe_ratio"] = info.get("trailingPE")
|
|
228
|
+
if pd.isna(df.at[idx, "pb_ratio"]) or df.at[idx, "pb_ratio"] == 0:
|
|
229
|
+
trading_currency = str(info.get("currency") or "")
|
|
230
|
+
financial_currency = str(info.get("financialCurrency") or trading_currency)
|
|
231
|
+
df.at[idx, "pb_ratio"] = sanitize_yahoo_pb(
|
|
232
|
+
info.get("priceToBook"),
|
|
233
|
+
trading_currency=trading_currency,
|
|
234
|
+
financial_currency=financial_currency,
|
|
235
|
+
)
|
|
236
|
+
if not df.at[idx, "industry"]:
|
|
237
|
+
df.at[idx, "industry"] = info.get("industry", "")
|
|
238
|
+
if not df.at[idx, "name"] or df.at[idx, "name"] == ticker:
|
|
239
|
+
df.at[idx, "name"] = info.get("shortName", ticker)
|
|
240
|
+
except Exception:
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def fetch_daily_history_yfinance(
|
|
245
|
+
ticker: str,
|
|
246
|
+
*,
|
|
247
|
+
lookback_days: int = 120,
|
|
248
|
+
) -> pd.DataFrame:
|
|
249
|
+
"""Fetch daily OHLCV history for a US ticker via yfinance.
|
|
250
|
+
|
|
251
|
+
Returns a DataFrame with columns: date, open, high, low, close, volume
|
|
252
|
+
matching the schema expected by alphasift.daily's enrichment logic.
|
|
253
|
+
"""
|
|
254
|
+
import yfinance as yf
|
|
255
|
+
|
|
256
|
+
# yfinance's end is exclusive: ask through tomorrow (UTC) so a session
|
|
257
|
+
# that has already closed is included. Callers drop in-progress bars.
|
|
258
|
+
end = pd.Timestamp.now(tz="UTC").normalize().tz_localize(None) + pd.Timedelta(days=2)
|
|
259
|
+
start = end - pd.Timedelta(days=max(lookback_days * 2, 180))
|
|
260
|
+
hist = yf.download(
|
|
261
|
+
ticker,
|
|
262
|
+
start=start.strftime("%Y-%m-%d"),
|
|
263
|
+
end=end.strftime("%Y-%m-%d"),
|
|
264
|
+
auto_adjust=True,
|
|
265
|
+
progress=False,
|
|
266
|
+
)
|
|
267
|
+
if hist is None or hist.empty:
|
|
268
|
+
raise RuntimeError(f"yfinance daily history empty for {ticker}")
|
|
269
|
+
|
|
270
|
+
if isinstance(hist.columns, pd.MultiIndex):
|
|
271
|
+
hist.columns = hist.columns.droplevel("Ticker")
|
|
272
|
+
|
|
273
|
+
hist = hist.tail(max(lookback_days, 30)).copy()
|
|
274
|
+
hist = hist.rename(columns={
|
|
275
|
+
"Open": "开盘", "High": "最高", "Low": "最低",
|
|
276
|
+
"Close": "收盘", "Volume": "成交量",
|
|
277
|
+
})
|
|
278
|
+
hist.index.name = "日期"
|
|
279
|
+
hist = hist.reset_index()
|
|
280
|
+
return hist
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Region-wide equity snapshot from the Yahoo Finance screener.
|
|
3
|
+
|
|
4
|
+
One query per sector tags every row with its sector, which portfolio
|
|
5
|
+
diversity control needs. A region above the market's universe floor is
|
|
6
|
+
typically 5-30 pages of 250 rows at ~0.3s each.
|
|
7
|
+
|
|
8
|
+
Field notes:
|
|
9
|
+
- ``amount`` is price x volume, an estimate of traded value.
|
|
10
|
+
``avg_amount`` is the current price x the 10-day average volume (3-month
|
|
11
|
+
when missing), an estimate whose volume part does not depend on the time
|
|
12
|
+
of day; ``avg_amount_usd`` converts it at the market's
|
|
13
|
+
approximate ``usd_rate`` for cross-market liquidity floors.
|
|
14
|
+
- ``volume_ratio`` is today's volume over the 10-day average. During the
|
|
15
|
+
session it reflects a partial day, like the A-share intraday volume ratio.
|
|
16
|
+
- ``circ_mv`` is total market cap; Yahoo has no free-float cap here.
|
|
17
|
+
- PE/PB are derived from trailing EPS and book value per share when Yahoo
|
|
18
|
+
omits the ratios. South Korea has neither; KR PE/PB come from Naver
|
|
19
|
+
Finance instead (``alphasift.valuation_kr``).
|
|
20
|
+
- Preferred shares are dropped (US ``-P`` symbols, KRX codes not ending in
|
|
21
|
+
0, Taiwan codes with a letter suffix). A company listed on two local
|
|
22
|
+
exchanges (India: NSE and BSE) is kept once.
|
|
23
|
+
- PB below 0.05 (e.g. dual-class share mismatches like BRK-B dividing Class B
|
|
24
|
+
price by Class A book value) or below 0.1 on a cross-currency listing (some
|
|
25
|
+
ADRs) is cleared as a reporting/currency artifact.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from datetime import datetime
|
|
31
|
+
import logging
|
|
32
|
+
import os
|
|
33
|
+
import re
|
|
34
|
+
import time
|
|
35
|
+
from zoneinfo import ZoneInfo
|
|
36
|
+
|
|
37
|
+
import pandas as pd
|
|
38
|
+
|
|
39
|
+
from alphasift.markets import MarketSpec, get_market
|
|
40
|
+
from alphasift.source_guard import parse_source_timeout_seconds
|
|
41
|
+
from alphasift.valuation_kr import enrich_kr_valuation, kr_valuation_enabled
|
|
42
|
+
|
|
43
|
+
logger = logging.getLogger(__name__)
|
|
44
|
+
|
|
45
|
+
YAHOO_SECTORS = (
|
|
46
|
+
"Basic Materials",
|
|
47
|
+
"Communication Services",
|
|
48
|
+
"Consumer Cyclical",
|
|
49
|
+
"Consumer Defensive",
|
|
50
|
+
"Energy",
|
|
51
|
+
"Financial Services",
|
|
52
|
+
"Healthcare",
|
|
53
|
+
"Industrials",
|
|
54
|
+
"Real Estate",
|
|
55
|
+
"Technology",
|
|
56
|
+
"Utilities",
|
|
57
|
+
)
|
|
58
|
+
_PREFERRED_SYMBOL_RE = re.compile(r"-P[A-Z]{0,2}$")
|
|
59
|
+
_TW_PREFERRED_RE = re.compile(r"\d{4}[A-Z]")
|
|
60
|
+
_MIN_PLAUSIBLE_PB = 0.05
|
|
61
|
+
_CROSS_CURRENCY_MIN_PB = 0.1
|
|
62
|
+
_PAGE_SIZE = 250
|
|
63
|
+
_PAGE_PAUSE_SECONDS = 0.2
|
|
64
|
+
_DEFAULT_MAX_ROWS = 4000
|
|
65
|
+
_DEFAULT_BUDGET_SECONDS = 90.0
|
|
66
|
+
_MIN_VALUATION_COVERAGE = 0.8
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def fetch_yahoo_snapshot(
|
|
70
|
+
market: str,
|
|
71
|
+
*,
|
|
72
|
+
min_market_cap: float | None = None,
|
|
73
|
+
max_rows: int | None = None,
|
|
74
|
+
screen=None,
|
|
75
|
+
) -> pd.DataFrame:
|
|
76
|
+
"""Return the standard snapshot schema for a Yahoo-screener market."""
|
|
77
|
+
spec = get_market(market)
|
|
78
|
+
if not spec.yahoo_region:
|
|
79
|
+
raise ValueError(f"Market {spec.id!r} is not served by the Yahoo screener")
|
|
80
|
+
if screen is None:
|
|
81
|
+
import yfinance as yf
|
|
82
|
+
|
|
83
|
+
screen = yf.screen
|
|
84
|
+
|
|
85
|
+
floor = spec.universe_min_market_cap if min_market_cap is None else float(min_market_cap)
|
|
86
|
+
limit = max_rows if max_rows is not None else _int_env("ALPHASIFT_YAHOO_MAX_ROWS", _DEFAULT_MAX_ROWS)
|
|
87
|
+
budget = parse_source_timeout_seconds(
|
|
88
|
+
"ALPHASIFT_YAHOO_SNAPSHOT_BUDGET_SEC", default=_DEFAULT_BUDGET_SECONDS
|
|
89
|
+
)
|
|
90
|
+
started = time.monotonic()
|
|
91
|
+
|
|
92
|
+
# A company listed on two exchanges (India) takes two raw rows, so a
|
|
93
|
+
# sector may need up to limit x suffixes rows to yield ``limit`` companies.
|
|
94
|
+
sector_row_cap = limit * max(1, len(spec.yahoo_suffixes))
|
|
95
|
+
rows: dict[str, dict[str, object]] = {}
|
|
96
|
+
errors: list[str] = []
|
|
97
|
+
timed_out = False
|
|
98
|
+
max_quote_time: float | None = None
|
|
99
|
+
for sector_index, sector in enumerate(YAHOO_SECTORS):
|
|
100
|
+
# Each sector is paged by market cap, up to ``limit`` rows of its own.
|
|
101
|
+
# The global top-``limit`` is then cut after all sectors are in, so a
|
|
102
|
+
# large early sector cannot crowd out Technology or Utilities.
|
|
103
|
+
offset = 0
|
|
104
|
+
while offset < sector_row_cap:
|
|
105
|
+
if budget is not None and time.monotonic() - started > budget:
|
|
106
|
+
# Keep what was fetched, marked partial: the caller then uses
|
|
107
|
+
# it without replacing the complete last-good cache, instead of
|
|
108
|
+
# dropping it and switching to a different universe.
|
|
109
|
+
skipped = ", ".join(YAHOO_SECTORS[sector_index:])
|
|
110
|
+
errors.append(
|
|
111
|
+
f"budget {budget:.0f}s exceeded after {len(rows)} rows; not fetched: {skipped}"
|
|
112
|
+
)
|
|
113
|
+
timed_out = True
|
|
114
|
+
break
|
|
115
|
+
try:
|
|
116
|
+
payload = screen(
|
|
117
|
+
_sector_query(spec, sector, floor),
|
|
118
|
+
size=_PAGE_SIZE,
|
|
119
|
+
offset=offset,
|
|
120
|
+
sortField="intradaymarketcap",
|
|
121
|
+
sortAsc=False,
|
|
122
|
+
)
|
|
123
|
+
except Exception as exc: # noqa: BLE001 - one sector failing should not drop the rest
|
|
124
|
+
errors.append(f"{sector}: {exc}")
|
|
125
|
+
break
|
|
126
|
+
quotes = (payload or {}).get("quotes") or []
|
|
127
|
+
for quote in quotes:
|
|
128
|
+
row = _quote_to_row(quote, sector)
|
|
129
|
+
if row is not None:
|
|
130
|
+
rows.setdefault(str(row["code"]), row)
|
|
131
|
+
quote_ts = _num(quote.get("regularMarketTime"))
|
|
132
|
+
if quote_ts is not None and quote_ts > 0:
|
|
133
|
+
max_quote_time = quote_ts if max_quote_time is None else max(max_quote_time, quote_ts)
|
|
134
|
+
offset += len(quotes)
|
|
135
|
+
total = int((payload or {}).get("total") or 0)
|
|
136
|
+
if not quotes or offset >= total:
|
|
137
|
+
break
|
|
138
|
+
time.sleep(_PAGE_PAUSE_SECONDS)
|
|
139
|
+
if timed_out:
|
|
140
|
+
break
|
|
141
|
+
|
|
142
|
+
if not rows:
|
|
143
|
+
detail = "; ".join(errors[:3]) or "no rows above the universe floor"
|
|
144
|
+
raise RuntimeError(f"yahoo_screener returned no data for market {spec.id}: {detail}")
|
|
145
|
+
|
|
146
|
+
df = _drop_secondary_listings(pd.DataFrame(list(rows.values())), spec)
|
|
147
|
+
df = df.sort_values("total_mv", ascending=False, na_position="last").head(limit).reset_index(drop=True)
|
|
148
|
+
df["avg_amount_usd"] = pd.to_numeric(df["avg_amount"], errors="coerce") / spec.usd_rate
|
|
149
|
+
valuation_errors: list[str] = []
|
|
150
|
+
valuation_incomplete = False
|
|
151
|
+
if spec.id == "kr" and kr_valuation_enabled():
|
|
152
|
+
# Yahoo has no PE/PB for Korean listings; Naver fills them within
|
|
153
|
+
# what is left of the snapshot budget (at most 60s).
|
|
154
|
+
remaining = 60.0 if budget is None else min(60.0, budget - (time.monotonic() - started))
|
|
155
|
+
if remaining <= 0:
|
|
156
|
+
# The snapshot budget is spent; do not run past it.
|
|
157
|
+
valuation_errors = ["naver_valuation skipped: snapshot budget exhausted"]
|
|
158
|
+
valuation_incomplete = True
|
|
159
|
+
else:
|
|
160
|
+
df, valuation_errors = enrich_kr_valuation(df, budget_seconds=remaining)
|
|
161
|
+
# A mostly unvalued frame must not replace a valued last-good cache.
|
|
162
|
+
valuation_incomplete = float(df.attrs.get("valuation_coverage", 1.0)) < _MIN_VALUATION_COVERAGE
|
|
163
|
+
df.attrs["snapshot_source"] = "yahoo_screener"
|
|
164
|
+
df.attrs["market"] = spec.id
|
|
165
|
+
df.attrs["currency"] = spec.currency
|
|
166
|
+
if max_quote_time is not None:
|
|
167
|
+
df.attrs["quote_date"] = (
|
|
168
|
+
datetime.fromtimestamp(max_quote_time, tz=ZoneInfo(spec.timezone))
|
|
169
|
+
.date()
|
|
170
|
+
.isoformat()
|
|
171
|
+
)
|
|
172
|
+
df.attrs["source_errors"] = [
|
|
173
|
+
*(f"yahoo_screener sector {item}" for item in errors),
|
|
174
|
+
*valuation_errors,
|
|
175
|
+
]
|
|
176
|
+
df.attrs["partial"] = bool(errors) or valuation_incomplete
|
|
177
|
+
logger.info("Yahoo screener snapshot for %s: %d rows", spec.id, len(df))
|
|
178
|
+
return df
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _sector_query(spec: MarketSpec, sector: str, floor: float):
|
|
182
|
+
from yfinance import EquityQuery
|
|
183
|
+
|
|
184
|
+
clauses = [
|
|
185
|
+
EquityQuery("eq", ["region", spec.yahoo_region]),
|
|
186
|
+
EquityQuery("eq", ["sector", sector]),
|
|
187
|
+
EquityQuery("gt", ["intradaymarketcap", floor]),
|
|
188
|
+
]
|
|
189
|
+
if spec.yahoo_exchanges:
|
|
190
|
+
clauses.append(EquityQuery("is-in", ["exchange", *spec.yahoo_exchanges]))
|
|
191
|
+
return EquityQuery("and", clauses)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def sanitize_yahoo_pb(
|
|
195
|
+
pb: object,
|
|
196
|
+
*,
|
|
197
|
+
trading_currency: str = "",
|
|
198
|
+
financial_currency: str = "",
|
|
199
|
+
) -> float | None:
|
|
200
|
+
"""Drop Yahoo P/B reporting/currency artifacts such as dual-class share mismatches."""
|
|
201
|
+
value = _num(pb)
|
|
202
|
+
if value is None or value <= 0 or value < _MIN_PLAUSIBLE_PB:
|
|
203
|
+
return None
|
|
204
|
+
if (
|
|
205
|
+
value < _CROSS_CURRENCY_MIN_PB
|
|
206
|
+
and financial_currency
|
|
207
|
+
and trading_currency
|
|
208
|
+
and financial_currency != trading_currency
|
|
209
|
+
):
|
|
210
|
+
return None
|
|
211
|
+
return value
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _quote_to_row(quote: dict, sector: str) -> dict[str, object] | None:
|
|
215
|
+
if str(quote.get("quoteType") or "EQUITY").upper() != "EQUITY":
|
|
216
|
+
return None
|
|
217
|
+
symbol = str(quote.get("symbol") or "").strip()
|
|
218
|
+
price = _num(quote.get("regularMarketPrice"))
|
|
219
|
+
if not symbol or price is None or price <= 0:
|
|
220
|
+
return None
|
|
221
|
+
if _PREFERRED_SYMBOL_RE.search(symbol):
|
|
222
|
+
# JPM-PC, BAC-PB...: preferred shares are tagged EQUITY by Yahoo.
|
|
223
|
+
return None
|
|
224
|
+
if _is_local_preferred(symbol):
|
|
225
|
+
return None
|
|
226
|
+
volume = _num(quote.get("regularMarketVolume"))
|
|
227
|
+
avg_volume = _num(quote.get("averageDailyVolume10Day")) or _num(quote.get("averageDailyVolume3Month"))
|
|
228
|
+
shares = _num(quote.get("sharesOutstanding"))
|
|
229
|
+
market_cap = _num(quote.get("marketCap"))
|
|
230
|
+
trading_currency = str(quote.get("currency") or "")
|
|
231
|
+
financial_currency = str(quote.get("financialCurrency") or trading_currency)
|
|
232
|
+
# EPS and book value are in the reporting currency. Dividing a USD price
|
|
233
|
+
# by JPY EPS gives a meaningless (tiny) ratio that would rank first in a
|
|
234
|
+
# low-PE screen, so only derive ratios when the currencies match.
|
|
235
|
+
same_currency = not financial_currency or not trading_currency or financial_currency == trading_currency
|
|
236
|
+
pe = _num(quote.get("trailingPE"))
|
|
237
|
+
if pe is None and same_currency:
|
|
238
|
+
eps = _num(quote.get("epsTrailingTwelveMonths"))
|
|
239
|
+
pe = price / eps if eps else None
|
|
240
|
+
pb = _num(quote.get("priceToBook"))
|
|
241
|
+
if pb is None and same_currency:
|
|
242
|
+
book = _num(quote.get("bookValue"))
|
|
243
|
+
pb = price / book if book and book > 0 else None
|
|
244
|
+
pb = sanitize_yahoo_pb(
|
|
245
|
+
pb,
|
|
246
|
+
trading_currency=trading_currency,
|
|
247
|
+
financial_currency=financial_currency,
|
|
248
|
+
)
|
|
249
|
+
dividend_yield = _num(quote.get("dividendYield"))
|
|
250
|
+
return {
|
|
251
|
+
"code": symbol,
|
|
252
|
+
"name": str(quote.get("longName") or quote.get("shortName") or symbol).strip(),
|
|
253
|
+
"price": price,
|
|
254
|
+
"change_pct": _num(quote.get("regularMarketChangePercent")),
|
|
255
|
+
"amount": price * volume if volume is not None else None,
|
|
256
|
+
"avg_amount": price * avg_volume if avg_volume is not None else None,
|
|
257
|
+
"total_mv": market_cap,
|
|
258
|
+
"circ_mv": market_cap,
|
|
259
|
+
"pe_ratio": pe,
|
|
260
|
+
"pb_ratio": pb,
|
|
261
|
+
"volume_ratio": (volume / avg_volume) if volume is not None and avg_volume else None,
|
|
262
|
+
"turnover_rate": (volume / shares * 100) if volume is not None and shares else None,
|
|
263
|
+
"industry": sector,
|
|
264
|
+
"dividend_yield": dividend_yield,
|
|
265
|
+
"currency": str(quote.get("currency") or ""),
|
|
266
|
+
"exchange": str(quote.get("fullExchangeName") or quote.get("exchange") or ""),
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _is_local_preferred(symbol: str) -> bool:
|
|
271
|
+
"""Preferred shares by local code convention.
|
|
272
|
+
|
|
273
|
+
KRX: common shares end in 0; 005935, 005387, 00088K are preferreds.
|
|
274
|
+
TWSE/TPEx: common shares are 4 digits; 2881A, 2891C, 2002A are preferreds.
|
|
275
|
+
"""
|
|
276
|
+
head, _, suffix = symbol.upper().rpartition(".")
|
|
277
|
+
if suffix in {"KS", "KQ"}:
|
|
278
|
+
return len(head) == 6 and head[-1] != "0"
|
|
279
|
+
if suffix in {"TW", "TWO"}:
|
|
280
|
+
return _TW_PREFERRED_RE.fullmatch(head) is not None
|
|
281
|
+
return False
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _drop_secondary_listings(df: pd.DataFrame, spec: MarketSpec) -> pd.DataFrame:
|
|
285
|
+
"""Keep one listing per company when it trades on two local exchanges.
|
|
286
|
+
|
|
287
|
+
Indian companies are listed on both NSE (RELIANCE.NS) and BSE
|
|
288
|
+
(RELIANCE.BO) under the same symbol; without this every company would be
|
|
289
|
+
screened, and could be picked, twice. The listing with more average
|
|
290
|
+
traded value (normally NSE) is kept.
|
|
291
|
+
|
|
292
|
+
This matches symbols, not company identity: a BSE listing under a
|
|
293
|
+
numeric scrip code would not be paired. KRX (KS/KQ) and TWSE/TPEx
|
|
294
|
+
(TW/TWO) codes are unique across their two boards, so nothing collapses
|
|
295
|
+
there.
|
|
296
|
+
"""
|
|
297
|
+
if len(spec.yahoo_suffixes) < 2 or df.empty:
|
|
298
|
+
return df
|
|
299
|
+
head = df["code"].astype(str).str.upper().str.rsplit(".", n=1).str[0]
|
|
300
|
+
# Rank by 10-day average traded value: today's volume can be missing or
|
|
301
|
+
# partial before the session and would keep the thin BSE listing.
|
|
302
|
+
today = pd.to_numeric(df["amount"], errors="coerce")
|
|
303
|
+
average = pd.to_numeric(df["avg_amount"], errors="coerce") if "avg_amount" in df.columns else today
|
|
304
|
+
order = average.fillna(today).fillna(-1.0)
|
|
305
|
+
keep = (
|
|
306
|
+
df.assign(_head=head, _order=order)
|
|
307
|
+
.sort_values("_order", ascending=False, kind="stable")
|
|
308
|
+
.drop_duplicates("_head", keep="first")
|
|
309
|
+
.index
|
|
310
|
+
)
|
|
311
|
+
return df.loc[sorted(keep)].reset_index(drop=True)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _num(value: object) -> float | None:
|
|
315
|
+
try:
|
|
316
|
+
number = float(value) # type: ignore[arg-type]
|
|
317
|
+
except (TypeError, ValueError):
|
|
318
|
+
return None
|
|
319
|
+
return number if number == number else None # drop NaN
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _int_env(name: str, default: int) -> int:
|
|
323
|
+
raw = os.getenv(name, "").strip()
|
|
324
|
+
return max(1, int(raw)) if raw else default
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def fetch_yahoo_quotes(symbols: list[str], *, download=None) -> pd.DataFrame:
|
|
328
|
+
"""Latest close for specific Yahoo symbols, outside the screener universe.
|
|
329
|
+
|
|
330
|
+
Evaluation needs current prices for saved picks even after they drop
|
|
331
|
+
below the market's universe floor; the screener would no longer return
|
|
332
|
+
them and they would be counted as missing instead of as losses.
|
|
333
|
+
"""
|
|
334
|
+
symbols = [str(item).strip().upper() for item in symbols if str(item).strip()]
|
|
335
|
+
if not symbols:
|
|
336
|
+
return pd.DataFrame(columns=["code", "price"])
|
|
337
|
+
if download is None:
|
|
338
|
+
import yfinance as yf
|
|
339
|
+
|
|
340
|
+
download = yf.download
|
|
341
|
+
data = download(
|
|
342
|
+
symbols,
|
|
343
|
+
period="5d",
|
|
344
|
+
auto_adjust=False,
|
|
345
|
+
group_by="ticker",
|
|
346
|
+
progress=False,
|
|
347
|
+
threads=True,
|
|
348
|
+
)
|
|
349
|
+
rows = []
|
|
350
|
+
for symbol in symbols:
|
|
351
|
+
try:
|
|
352
|
+
frame = data[symbol] if isinstance(data.columns, pd.MultiIndex) else data
|
|
353
|
+
close = pd.to_numeric(frame["Close"], errors="coerce").dropna()
|
|
354
|
+
except (KeyError, TypeError):
|
|
355
|
+
continue
|
|
356
|
+
if not close.empty and float(close.iloc[-1]) > 0:
|
|
357
|
+
rows.append({"code": symbol, "price": float(close.iloc[-1])})
|
|
358
|
+
return pd.DataFrame(rows, columns=["code", "price"])
|