Files

240 lines
10 KiB
Python

"""Validated Yahoo Finance daily fallback for the active SET liquid universe."""
from __future__ import annotations
from collections.abc import Iterable
from datetime import date, timedelta
import csv
import io
import math
from pathlib import Path
import re
import pandas as pd
from .data import yahoo_symbol
from .model_lab import load_market_panel
MIN_LIQUID_UNIVERSE_COVERAGE = 0.95
LIQUID_UNIVERSE_SIZE = 100
YAHOO_BATCH_SIZE = 100
_TICKER = re.compile(r"[A-Z0-9]{1,5}$")
_EOD_COLUMNS = ["<TICKER>", "<DTYYYYMMDD>", "<OPEN>", "<HIGH>", "<LOW>", "<CLOSE>", "<VOL>"]
class YahooBackupError(RuntimeError):
"""The secondary source could not produce a complete, validated EOD session."""
def _expected_liquid_symbols(archives: list[str | Path], latest_date: str) -> tuple[list[str], list[str]]:
latest = pd.Timestamp(latest_date)
start = (latest - pd.Timedelta(days=120)).date().isoformat()
end = (latest + pd.Timedelta(days=1)).date().isoformat()
panel = load_market_panel(
[str(path) for path in archives],
start=start,
end=end,
action_dir="data/raw/actions",
set_index_csv="data/raw/^SET.csv",
set_reference="data/reference/set_actions_2025_2026_h1.csv",
)
if not len(panel.dates) or panel.dates[-1].date().isoformat() != latest_date:
raise YahooBackupError("หา session ล่าสุดในไฟล์ราคาที่เก็บไว้เพื่อเทียบ coverage ไม่พบ")
turnover = panel.close.mul(panel.volume.where(panel.has_bar, 0.0))
average_turnover = turnover.rolling(20, min_periods=20).mean().iloc[-1]
close = panel.close.iloc[-1]
eligible = panel.has_bar.iloc[-1] & close.ge(2.0) & average_turnover.ge(20_000_000.0)
ranked = average_turnover.where(eligible).dropna().sort_values(ascending=False, kind="stable")
expected = [symbol for symbol in ranked.index[:LIQUID_UNIVERSE_SIZE].tolist()
if _TICKER.fullmatch(str(symbol))]
requested = [str(symbol) for symbol in panel.symbols if _TICKER.fullmatch(str(symbol))]
if len(expected) < LIQUID_UNIVERSE_SIZE:
raise YahooBackupError(
f"ชุดราคาที่เก็บไว้มีหุ้นผ่านเกณฑ์สภาพคล่องเพียง {len(expected)} ตัว; ตรวจ Yahoo fallback ไม่ได้"
)
return expected, requested
def _frame_for_ticker(frame: pd.DataFrame, ticker: str, batch: list[str]) -> pd.DataFrame | None:
if not isinstance(frame.columns, pd.MultiIndex):
return frame if len(batch) == 1 else None
wanted = ticker.upper()
for level in range(frame.columns.nlevels):
values = frame.columns.get_level_values(level)
actual = next((str(value) for value in values.unique() if str(value).upper() == wanted), None)
if actual is None:
continue
selected = frame.xs(actual, axis=1, level=level, drop_level=True)
if isinstance(selected.columns, pd.MultiIndex):
selected.columns = [str(column[-1]) for column in selected.columns]
return selected
return None
def _date_key(value: object) -> str:
stamp = pd.Timestamp(value)
if stamp.tzinfo is not None:
stamp = stamp.tz_convert("Asia/Bangkok").tz_localize(None)
return stamp.date().isoformat()
def _extract_bars(frame: pd.DataFrame | None, *, allow_missing_volume: bool = False) -> dict[str, dict[str, float]]:
if frame is None or frame.empty:
return {}
columns = {str(column).strip().casefold().replace(" ", "_"): column
for column in frame.columns}
required = {"open", "high", "low", "close", "volume"}
if not required.issubset(columns):
return {}
result: dict[str, dict[str, float]] = {}
for index, row in frame.iterrows():
try:
bar = {field: float(row[columns[field]]) for field in required}
except (TypeError, ValueError, KeyError):
if not allow_missing_volume:
continue
try:
bar = {field: float(row[columns[field]]) for field in required - {"volume"}}
bar["volume"] = 0.0
except (TypeError, ValueError, KeyError):
continue
if allow_missing_volume and not math.isfinite(bar.get("volume", 0.0)):
bar["volume"] = 0.0
if not all(math.isfinite(value) for value in bar.values()):
continue
if min(bar["open"], bar["high"], bar["low"], bar["close"]) <= 0 or bar["volume"] < 0:
continue
if bar["high"] + 1e-8 < max(bar["open"], bar["close"], bar["low"]):
continue
if bar["low"] - 1e-8 > min(bar["open"], bar["close"], bar["high"]):
continue
result[_date_key(index)] = bar
return result
def _download_yahoo(tickers: list[str], *, start: str, end: str) -> tuple[dict[str, dict[str, dict[str, float]]], list[str]]:
try:
import yfinance as yf
except ImportError as exc:
raise YahooBackupError("ไม่พบ yfinance ใน environment ของแอป") from exc
bars: dict[str, dict[str, dict[str, float]]] = {}
errors: list[str] = []
unique = list(dict.fromkeys(tickers))
for offset in range(0, len(unique), YAHOO_BATCH_SIZE):
batch = unique[offset:offset + YAHOO_BATCH_SIZE]
try:
data = yf.download(
batch,
start=start,
end=end,
interval="1d",
auto_adjust=False,
actions=False,
repair=False,
progress=False,
threads=8,
group_by="ticker",
ignore_tz=True,
timeout=20,
multi_level_index=True,
)
except Exception as exc:
errors.append(f"batch {offset // YAHOO_BATCH_SIZE + 1}: {type(exc).__name__}")
continue
if data is None or data.empty:
errors.append(f"batch {offset // YAHOO_BATCH_SIZE + 1}: no data")
continue
for ticker in batch:
frame = _frame_for_ticker(data, ticker, batch)
normalized = _extract_bars(frame, allow_missing_volume=ticker == "^SET.BK")
if normalized:
bars[ticker] = normalized
return bars, errors
def _csv_bytes(day: str, bars: dict[str, dict[str, float]]) -> bytes:
text = io.StringIO(newline="")
writer = csv.DictWriter(text, fieldnames=_EOD_COLUMNS, lineterminator="\n")
writer.writeheader()
yyyymmdd = day.replace("-", "")
for ticker, bar in sorted(bars.items()):
writer.writerow({
"<TICKER>": ticker,
"<DTYYYYMMDD>": yyyymmdd,
"<OPEN>": format(bar["open"], ".10g"),
"<HIGH>": format(bar["high"], ".10g"),
"<LOW>": format(bar["low"], ".10g"),
"<CLOSE>": format(bar["close"], ".10g"),
"<VOL>": format(bar["volume"], ".10g"),
})
return text.getvalue().encode("utf-8")
def fetch_yahoo_eod_backup(
archives: list[str | Path],
*,
latest_date: str,
end_date: date,
required_symbols: Iterable[str] = (),
) -> tuple[dict[str, bytes], dict[str, dict[str, object]]]:
"""Fetch missing EOD sessions for the liquid model universe from Yahoo.
The index and at least 95% of the prior session's top-100 liquid universe
must have a valid Yahoo bar for each session before any rows are returned.
"""
expected, requested = _expected_liquid_symbols(archives, latest_date)
extras = {str(symbol).strip().upper() for symbol in required_symbols
if _TICKER.fullmatch(str(symbol).strip().upper())}
symbols = sorted(set(requested) | set(expected) | extras)
ticker_to_symbol = {yahoo_symbol(symbol): symbol for symbol in symbols}
set_ticker = yahoo_symbol("^SET")
start = latest_date
end = (end_date + timedelta(days=1)).isoformat()
index_rows, index_errors = _download_yahoo([set_ticker], start=start, end=end)
index_bars = index_rows.get(set_ticker, {})
if not index_bars:
detail = "; ".join(index_errors[:2])
raise YahooBackupError("Yahoo ไม่มีแท่งข้อมูล SET สำหรับยืนยัน session" + (f" ({detail})" if detail else ""))
symbol_rows, batch_errors = _download_yahoo(list(ticker_to_symbol), start=start, end=end)
market_bars: dict[str, dict[str, dict[str, float]]] = {
ticker_to_symbol[ticker]: rows for ticker, rows in symbol_rows.items()
if ticker in ticker_to_symbol
}
new_days = sorted(day for day in index_bars if day > latest_date)
if not new_days:
raise YahooBackupError("Yahoo ยังไม่มีข้อมูล SET หลังวันที่เก็บไว้ล่าสุด")
merged: dict[str, bytes] = {}
metadata: dict[str, dict[str, object]] = {}
expected_count = len(expected)
for day in new_days:
available = {symbol for symbol, rows in market_bars.items() if day in rows}
coverage_count = len(set(expected) & available)
coverage = coverage_count / expected_count if expected_count else 0.0
if coverage < MIN_LIQUID_UNIVERSE_COVERAGE:
raise YahooBackupError(
f"Yahoo coverage หุ้นสภาพคล่องหลัก {coverage_count}/{expected_count} ตัว "
f"({coverage:.0%}); ต้องได้อย่างน้อย {MIN_LIQUID_UNIVERSE_COVERAGE:.0%}"
)
daily: dict[str, dict[str, float]] = {symbol: rows[day] for symbol, rows in market_bars.items()
if day in rows}
daily["SET"] = index_bars[day]
missing_positions = sorted(symbol for symbol in extras if symbol not in available)
if missing_positions:
raise YahooBackupError(
"Yahoo ไม่มีราคาวันล่าสุดของหุ้นที่ถืออยู่/สัญญาณสำคัญ: "
+ ", ".join(missing_positions[:8])
)
merged[day] = _csv_bytes(day, daily)
metadata[day] = {
"source": "Yahoo Finance via yfinance",
"records": len(daily),
"liquid_universe_coverage": coverage,
"liquid_universe_present": coverage_count,
"liquid_universe_expected": expected_count,
"batch_errors": batch_errors[:5],
}
return merged, metadata